Module 15 - 20 C# Advanced
Module 15 - 20 C# Advanced
By
SRIRAM . B
C# Advanced
Generics are classes, structures, interfaces, and methods that have placeholders
(type parameters) for one or more of the types they store or use.
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.
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;
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();
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.
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.
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.
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;
The HasValue property returns true if the variable contains a value, or false if it
is null.
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("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
// 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.
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
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..
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