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.
REMARKS
·Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace. All the parts must use the partial keyword. All of the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.
·If any of the parts are declared abstract, then the entire type is considered abstract. If any of the parts are declared sealed, then the entire type is considered sealed. If any of the parts declare a base type, then the entire type inherits that class.
·All of the parts that specify a base class must agree, but parts that omit a base class still inherit the base type. Parts can specify different base interfaces, and the final type implements all of the interfaces listed by all of the partial declarations. Any class, struct, or interface members declared in a partial definition are available to all of the other parts. The final type is the combination of all the parts at compile time.
A class can inherit implementation from one base class only. However, a class can implement more than one interface
A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type. Programmers can then create objects that are instances of this class. Unlike structures, classes support inheritance, a fundamental part of object-oriented programming
Structs have the following properties:
· Structs are value types while classes are reference types.
· Unlike classes, structs can be instantiated without using a new operator.
· Structs can declare constructors, but they must take parameters.
· A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
·A struct can implement interfaces.
·Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
·A struct may not declare a default constructor —a constructor with no parameters — or a destructor.
Indexers Overview
Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties except that their accessors take parameters.
·Indexers enable objects to be indexed in a similar way to arrays.
·A get accessor returns a value. A set accessor assigns a value.
·The this keyword is used to define the indexers.
·The value keyword is used to define the value being assigned by the set indexer.
·Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.
·Indexers can be overloaded.
·Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.
class SampleCollection
{
private T[] arr = new T[100];
public T this[int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}
// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args)
{
SampleCollection
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
Delegates (C# Programming Guide)
A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value
public delegate int PerformCalculation(int x, int y);
Delegates Overview
Delegates have the following properties:
·Delegates are similar to C++ function pointers, but are type safe.
·Delegates allow methods to be passed as parameters.
·Delegates can be used to define callback methods.
·Delegates can be chained together; for example, multiple methods can be called on a single event.
·Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contravariance
·C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.
Events Overview
Events have the following properties:
·The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.
·An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.
·Events that have no subscribers are never called.
·Events are commonly used to signal user actions such as button clicks or menu selections in graphical user interfaces.
·When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events asynchronously, see Calling Synchronous Methods Asynchronously.
·Events can be used to synchronize threads.
·In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.
Generics Overview
·Use generic types to maximize code reuse, type safety, and performance.
·The most common use of generics is to create collection classes.
·The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.
·You can create your own generic interfaces, classes, methods, events and delegates.
·Generic classes may be constrained to enable access to methods on particular data types.
·Information on the types used in a generic data type may be obtained at run-time by means of reflection.
Defination: using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:
// Declare the generic class
public class GenericList
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int
GenericList
// Declare a list of type string
GenericList
// Declare a list of type ExampleClass
GenericList
}
}
Arrays (C# Programming Guide)
An array is a data structure that contains a number of variables of the same type. Arrays are declared with a type:
type[] arrayName;
class TestArraysClass
{
static void Main()
{
// Declare a single-dimensional array
int[] array1 = new int[5];
// Declare and set array element values
int[] array2 = new int[] { 1, 3, 5, 7, 9 };
// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5, 6 };
// Declare a two dimensional array
int[,] multiDimensionalArray1 = new int[2, 3];
// Declare and set array element values
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
// Declare a jagged array
int[][] jaggedArray = new int[6][];
// Set the values of the first array in the jagged array structure
jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
}
}
Array Overview
An array has the following properties:
· An array can be Single-Dimensional, Multidimensional or Jagged.
· The default value of numeric array elements are set to zero, and reference elements are set to null.
· A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.
· Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.
· Array elements can be of any type, including an array type.
· Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable, you can use foreach iteration on all arrays in C#.
virtual (C# Reference)
The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it
public virtual double Area()
{
return x * y;
}
Remarks
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
By default, methods are non-virtual. You cannot override a non-virtual method.
You cannot use the virtual modifier with the static, abstract, private, or override modifiers.
Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.
·It is an error to use the virtual modifier on a static property.
·A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
static (C# Reference)
·Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. For example, the following class is declared as static and contains only static methods:
static class CompanyEmployee
{
public static string GetCompanyName(string name) { ... }
public static string GetCompanyAddress(string address) { ... }
}
Remarks
·A constant or type declaration is implicitly a static member.
·A static member cannot be referenced through an instance. Instead, it is referenced through the type name. For example, consider the following class:
public class MyBaseC
{
public struct MyStruct
{
public static int x = 100;}}
·To refer to the static member x, use the fully qualified name (unless it is accessible from the same scope):
MyBaseC.MyStruct.x
·While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.
·It is not possible to use this to reference static methods or property accessors.
·If the static keyword is applied to a class, all the members of the class must be static.
·Classes and static classes may have static constructors. Static constructors are called at some point between when the program starts and the class is instantiated.
To demonstrate static members, consider a class that represents a company employee. Assume that the class contains a method to count employees and a field to store the number of employees. Both the method and the field do not belong to any instance employee. Instead they belong to the company class. Therefore, they should be declared as static members of the class.
sealed (C# Reference)
When applied to a class, the sealed modifier prevents other classes from inheriting from it. In the following example, class B inherits from class A, but no class can inherit from class B
class A {}
sealed class B : A {}
You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties. In the following example, C inherits from B but C cannot override the virtual function F that is declared in A and sealed in B.
class A
{
protected virtual void F() { Console.WriteLine("A.F");}
protected virtual void F2() { Console.WriteLine("A.F2");}
}
class B : A
{
sealed protected override void F() { Console.WriteLine("B.F");}
protected override void F2() {Console.WriteLine("A.F3");}
}
class C : B
{
// Attempting to override F causes compiler error CS0239.
// protected override void F() { Console.WriteLine("C.F"); }
// Overriding F2 is allowed.
protected override void F2() { Console.WriteLine("C.F2"); }
}
No comments:
Post a Comment