Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
54 views

Module 15 - 20 C# Advanced

This document provides an overview of C# advanced topics including generics, partial types, nullable types, iterators, anonymous methods, and static classes. Module 15 discusses generics which allow classes and methods to work with unknown types. Module 16 covers partial types which allow splitting class definitions across multiple files. Module 17 focuses on nullable types which allow value types like integers to include a null value. The examples demonstrate how to use generics, partial classes, and nullable types in C# code.

Uploaded by

api-19796528
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Module 15 - 20 C# Advanced

This document provides an overview of C# advanced topics including generics, partial types, nullable types, iterators, anonymous methods, and static classes. Module 15 discusses generics which allow classes and methods to work with unknown types. Module 16 covers partial types which allow splitting class definitions across multiple files. Module 17 focuses on nullable types which allow value types like integers to include a null value. The examples demonstrate how to use generics, partial classes, and nullable types in C# code.

Uploaded by

api-19796528
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 56

C# ADVANCED

By
SRIRAM . B
C# Advanced

 Module 15: Generics


 Module 16: Partial Types
 Module 17: Nullable Types
 Module 18: Iterator
 Module 19: Anonymous Methods
 Module 20: Static Classes
Module 15 :
Generics
Generics

 Generics are classes, structures, interfaces, and methods that have placeholders
(type parameters) for one or more of the types they store or use.

 Available in System.Collections.Generics namespace.

 A generic collection class might use a type parameter as a placeholder for the
type of objects it stores; the type parameters appear as the types of its fields, and
the parameter types of its methods.

 A generic method might use its type parameter as the type of its return value, or
as the type of one of its formal parameters. The following code illustrates a simple
generic class definition.
Generics..
public class Generic<T>
{
public T Field;
}

 When you create an instance of a generic class, you specify the actual types to
substitute for the type parameters. This establishes a new generic class, referred to
as a constructed generic class, with your chosen types substituted everywhere that
the type parameters appear. The result is a type-safe class tailored to your choice
of types, as the following code illustrates.
Generic<string> g = new Generic<string>();
g.Field = "A string";
Generics Method
 A generic method definition is a method with two parameter lists: a list of generic
type parameters, and a list of formal parameters. Type parameters can appear as
the return type or as the types of the formal parameters, as in the following code.

T Generic<T>(T arg) { T temp = arg; ...}

 Generic methods can appear on generic or nongeneric types. It is important to note


that a method is not generic just because it belongs to a generic type, or even
because it has formal parameters whose types are the generic parameters of the
enclosing type. A method is generic only if it has its own list of type parameters. In
the following code, only method G is generic.
Generics Method

class A
{
T G<T>(T arg) {...}
}
class Generic<T>
{
T M(T arg) {...}
}
Example 1 - Generics
using System;
using System.Collections.Generic;
using System.Text;

//Generic classes and methods combine reusability,


//type safety and efficiency in a way that their
non-generic counterparts cannot.
Example 1 - Generics..
namespace GenericsExample
{
class myclass
{
//Type parameters T,W in angled brackets
public void disp1<T, W>(T a, W b)
{
int cc;
Console.WriteLine(a + " " + b);
Console.WriteLine(a.GetType());
}
}
Example 1 - Generics..
class Program
{
static void Main(string[] args)
{
myclass ob = new myclass();
ob.disp1<int, int>(10, 20);
ob.disp1<float, string>(23.2f, "Bye");
ob.disp1<string, int>("Hello", 101);
}
}
}
Example 2 - Generics
using System;
using System.Collections.Generic;
using System.Text;

namespace GenericsExample
{
public delegate void mydelegate<T, W>(T a, W b);

class Class2
{
public void disp1<T, W>(T a, W b)
{
Console.WriteLine(a + " " + b);
}
Example 2 - Generics..
class mainclass
{
static void Main(string[] ar)
{
Class2 ob = new Class2();

mydelegate<int, string> obj =


new mydelegate<int, string>(ob.disp1);

mydelegate<float, int> obj1 =


new mydelegate<float, int>(ob.disp1);

obj(101, "Aaa");
obj1(10.2f, 100);
}
}
}
Module 16 :
Partial Types
Partial Types
 It is possible to split the definition of a class or a struct, or an interface over two or
more source files. Each source file contains a section of the class definition, and all
parts are combined when the application is compiled.

 There are several situations when splitting a class definition is desirable:

 When working on large projects, spreading a class over separate files allows
multiple programmers to work on it simultaneously.

 When working with automatically generated source, code can be added to the
class without having to recreate the source file. Visual Studio uses this
approach when creating Windows Forms, Web Service wrapper code, and so
on. You can create code that uses these classes without having to edit the file
created by Visual Studio.
Partial Types..
 To split a class definition, use the partial keyword modifier, as shown below:
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
} }
Example 1 – Partial Main
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericsExample
{ class mainclass
{
static void Main(string[] ar)
{
Special s = new Special();
s.first();
s.second();
s.third();
s.four();
}
}
}
Example 1 – Partial 1

using System;
using System.Collections.Generic;
using System.Text;
namespace GenericsExample
{
public partial class Special
{
public void first()
{
Console.WriteLine("First Partial");
}
public void second()
{
Console.WriteLine("Second Partial");
}
}
}
Example 1 – Partial 2
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericsExample
{
public partial class Special
{
public void third()
{
Console.WriteLine("Third Partial");
}
public void four()
{
Console.WriteLine("Four Partial");
}
}
}
Module 17 :
Nullable Types
Nullable Types
 Nullable types are instances of the System.Nullable struct.
 A nullable type can represent the normal range of values for its
underlying value type, plus an additional null value.

For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any


value from -2147483648 to 2147483647, or it can be assigned the null value.
Nullable Types..

 A Nullable<bool> can be assigned the values true or false, or null. The ability to
assign null to numeric and Boolean types is particularly useful when dealing with
databases and other data types containing elements that may not be assigned a
value.

For example, a Boolean field in a database can store the values


true or false, or it may be undefined.
Characteristics of Nullable Types
 Nullable types represent value-type variables that can be assigned the value of null.
You cannot create a nullable type based on a reference type. (Reference types
already support the null value.)

 The syntax T? is shorthand for System.Nullable<T>, where T is a value type. The


two forms are interchangeable.

 Assign a value to a nullable type in the same way as for an ordinary value type, for
example int? x = 10; or double? D = 4.108;

 Use the System.Nullable.GetValueOrDefault property to return either the assigned


value, or the default value for the underlying type if the value is null, for example int
j = x.GetValueOrDefault();
Characteristics of Nullable Types..
 Use the HasValue and Value read-only properties to test for null and retrieve the
value, for example if(x.HasValue) j = x.Value;

 The HasValue property returns true if the variable contains a value, or false if it
is null.

 The Value property returns a value if one is assigned, otherwise a


System.InvalidOperationException is thrown.

 The default value for a nullable type variable sets HasValue to false. The
Value is undefined.

 Use the ?? operator to assign a default value that will be applied when a nullable
type whose current value is null is assigned to a non-nullable type, for example int?
x = null; int y = x ?? -1;
Example 1 – Nullable Types
using System;
using System.Collections.Generic;
using System.Text;

namespace NullableTypes
{
class Class1
{
static void Main(string[] args)
{
int? a = null;
int b;
int? C;
int d;
Example 1 – Nullable Types..

Console.WriteLine("enter a number for B");


b = Convert.ToInt16(Console.ReadLine());
c = a + b;

Console.WriteLine("A(null)+B(normal)=C(Null)
result:" + c);
d = a ?? +b;

Console.WriteLine(" A(null)+B(normal)=d(Normal)
result:" + d);
Example 1 – Nullable Types..

if (b is int)
{
d = b + b;
Console.WriteLine("is result:" + d);
}
else
{
Console.WriteLine("mismatched datatypes");
}

}
class sub
{
}
}
}
Example 2 – Nullable Types
using System;
using System.Collections.Generic;
using System.Text;
namespace NullableTypes
{
class NullableExample
{
static void Main()
{
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
Example 2 – Nullable Types

//y is set to zero


int y = num.GetValueOrDefault();

// num.Value throws an
InvalidOperationException if num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}

}
Module 18 :
Iterator
Iterator
 Iterator is a section of code that returns an ordered sequence of values of the same
type.

 An iterator can be used as the body of a method, an operator, or a get accessor.

 The iterator code uses the yield return statement to return each element in turn.
yield break ends the iteration. For more information, see yield.

 Multiple iterators can be implemented on a class. Each iterator must have a unique
name just like any class member, and can be invoked by client code in a foreach
statement as follows: foreach(int x in SampleClass.Iterator2){}
Iterator..
 The return type of an iterator must be IEnumerable, IEnumerator, IEnumerable, or
IEnumerator.

 The “yield” keyword is used to specify the value, or values, returned. When the
yield return statement is reached, the current location is stored. Execution is
restarted from this location the next time the iterator is called.

 Iterators are especially useful with collection classes, providing an easy way to
iterate non-trivial data structures such as binary trees.
Example 1- Iterator

using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number,int
exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
Example 1- Iterator..
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 50))
{
Console.Write("{0} ", i);
}
}
}
Using
Using
using System;
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}
public void first()
{
Console.WriteLine("statement from first
method");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited
resource.");
}
}
Using..
class Program
{
static void Main()
{
using (C c = new C())
//C c = new C();
{
c.UseLimitedResource();
c.first();
}
Console.WriteLine("Now outside using
statement.");
Console.ReadLine();
}
}
Module 19 :
Anonymous Methods
Anonymous Methods
 Creating anonymous methods is essentially a way to pass a code block as a
delegate parameter

// Create a handler for a click event


button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };

// Create a delegate instance


delegate void Del(int x);

// Instantiate the delegate using an anonymous method


Del d = delegate(int k) { /* ... */ };
Anonymous Methods..

 By using anonymous methods, you reduce the coding overhead in instantiating


delegates by eliminating the need to create a separate method.

 For example, specifying a code block in the place of a delegate can be useful in a
situation when having to create a method might seem an unnecessary overhead. A
good example would be when launching a new thread. This class creates a thread
and also contains the code that the thread executes, without the need for creating
an additional method for the delegate.
Anonymous Methods..
void StartThread()
{
System.Threading.Thread t1 = new System.Threading.Thread
(delegate()
{
System.Console.Write("Hello, ");
System.Console.WriteLine("World!");
});
t1.Start();
}
Example 1 – Anonymous Methods
using System;
using System.Collections.Generic;
using System.Text;

// Declare a delegate
delegate void Printer(string s);
class TestClass
{
static void Main()
{
// Instatiate the delegate type using an anonymous
method:
Printer p = delegate(string j)
{
System.Console.WriteLine(j);
}
Example 1 – Anonymous Methods..
// Results from the anonymous delegate call:
p("The delegate using the anonymous method is
called.");
// The delegate instantiation using a named method
"DoWork":
p = new Printer(TestClass.DoWork);
// Results from the old style delegate call:
p("The delegate using the named method is
called.");
}
// The method associated with the named delegate:
static void DoWork(string k)
{
System.Console.WriteLine(k);
}
}
Example 2 – Anonymous Methods

using System;
using System.Collections.Generic;
using System.Text;

namespace test
{
delegate void mydelegate(int i);
class anonymousmethod2
{
Example 2 – Anonymous Methods..

static void Main(string[] args)


{
mydelegate dele = delegate(int i)
{
int j = i + 10;
Console.WriteLine("value is :" + j);
};
Console.WriteLine("enter a value");
int kk = Convert.ToInt16(Console.ReadLine());

dele(kk);
dele = new mydelegate(tt);//non....
dele(kk);//similar like tt(kk)..
dele = new mydelegate(ttt);//non....
dele(kk);//similar like ttt(kk)..
}
Example 2 – Anonymous Methods
public static void tt(int i)
{
int j = i + 5;
Console.WriteLine("value from non is :" + j);
}
public static void ttt(int i)
{
int j = i + 20;
Console.WriteLine("value from non is :" + j);
}
}
}
Module 20 :
Static Class
Static Class

 Static classes and class members are used to create data and functions that can
be accessed without creating an instance of the class.

 Static class members can be used to separate data and behavior that is
independent of any object identity: the data and functions do not change regardless
of what happens to the object.

 Static classes can be used when there is no data or behavior in the class that
depends on object identity.
Static Class..

 A class can be declared “static”, indicating that it contains only static members. It is
not possible to create instances of a static class using the new keyword. Static
classes are loaded automatically by the .NET Framework common language
runtime (CLR) when the program or namespace containing the class is loaded.

 Use a “static” class to contain methods that are not associated with a particular
object. For example, it is a common requirement to create a set of methods that do
not act on instance data and are not associated to a specific object in your code.
You could use a static class to hold those methods. 
Static Class..
 The main features of a static class are:
 They only contain static members.
 They cannot be instantiated.
 They are sealed.
 They cannot contain Instance
Example 1 - Static Class

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
static class second
{
static void Main(string[] args)
{
second.s1();
}
Example 1 – Static Class

public static void s1()


{
Console.WriteLine("infor from the meth s1 for
first class");
}

public void s2()


{
Console.WriteLine("infor from the meth s2 for
first class");
}
}
}
Example 2 – Static Class
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class second
{
static void Main(string[] args)
{
second.s1();
second.s2();
}
Example 2 – Static Class

public static void s1()


{
Console.WriteLine("infor from the meth s1 for
first class");
}
public static void s2()
{
Console.WriteLine("infor from the meth s2
for first class");
}
}
}
Session Ends
Exercise
Relax

You might also like