A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.
Method Signatures
Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.
abstract class Motorcycle
{
// Anyone can call this.
public void StartEngine() {/* Method statements here */ }
// Only derived classes can call this.
protected void AddGas(int gallons) { /* Method statements here */ }
// Derived classes can override the base class implementation.
public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; }
// Derived classes must implement this.
public abstract double GetTopSpeed();
}
Method Access
Calling a method on an object is like accessing a field. After the object name, add a period, the name of the method, and parentheses. Arguments are listed within the parentheses, and are separated by commas. The methods of the Motorcycle class can therefore be called as in the following example:
class TestMotorcycle : Motorcycle
{
public override double GetTopSpeed()
{
return 108.4;
}
static void Main()
{
TestMotorcycle moto = new TestMotorcycle();
moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);
double speed = moto.GetTopSpeed();
Console.WriteLine("My top speed is {0}", speed);
}
}
Method Parameters vs. Arguments
The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method. For example:
public void Caller()
{
int numA = 4;
// Call with an int variable.
int productA = Square(numA);
int numB = 32;
// Call with another int variable.
int productB = Square(numB);
// Call with an integer literal.
int productC = Square(12);
// Call with an expression that evaulates to int.
productC = Square(productA * 3);
}
int Square(int i)
{
// Store input argument in a local variable.
int input = i;
return input * input;
}
Passing by Reference vs. Passing by Value
By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method. You can pass a value-type by reference by using the ref keyword. For more information, see Passing Value-Type Parameters . For a list of built-in value types.
Reference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy. Changes made through this reference will therefore be reflected in the calling method. A reference type is created by using the class keyword as in the following example:
public class SampleRefType
{
public int value;
}
Now, if an object that is based on this type is passed to a method, the object will be passed by reference. For example:
public static void TestRefType()
{
SampleRefType rt = new SampleRefType();
rt.value = 44;
ModifyObject(rt);
Console.WriteLine(rt.value);
}
static void ModifyObject(SampleRefType obj)
{
obj.value = 33;
}
Return Values
Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, the method can return the value by using the return keyword. A statement with the return keyword followed by a value that matches the return type will return that value to the method caller. The return keyword also stops the execution of the method. If the return type is void, a return statement without a value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block. Methods with a non-void return type are required to use the return keyword to return a value. For example, these two methods use the return keyword to return integers:
int result = obj.AddTwoNumbers(1, 2);
result = obj.SquareANumber(result);
// The result is 9.
Console.WriteLine(result)
source: MSDN
Method Signatures
Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.
abstract class Motorcycle
{
// Anyone can call this.
public void StartEngine() {/* Method statements here */ }
// Only derived classes can call this.
protected void AddGas(int gallons) { /* Method statements here */ }
// Derived classes can override the base class implementation.
public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; }
// Derived classes must implement this.
public abstract double GetTopSpeed();
}
Method Access
Calling a method on an object is like accessing a field. After the object name, add a period, the name of the method, and parentheses. Arguments are listed within the parentheses, and are separated by commas. The methods of the Motorcycle class can therefore be called as in the following example:
class TestMotorcycle : Motorcycle
{
public override double GetTopSpeed()
{
return 108.4;
}
static void Main()
{
TestMotorcycle moto = new TestMotorcycle();
moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);
double speed = moto.GetTopSpeed();
Console.WriteLine("My top speed is {0}", speed);
}
}
Method Parameters vs. Arguments
The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method. For example:
public void Caller()
{
int numA = 4;
// Call with an int variable.
int productA = Square(numA);
int numB = 32;
// Call with another int variable.
int productB = Square(numB);
// Call with an integer literal.
int productC = Square(12);
// Call with an expression that evaulates to int.
productC = Square(productA * 3);
}
int Square(int i)
{
// Store input argument in a local variable.
int input = i;
return input * input;
}
Passing by Reference vs. Passing by Value
By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method. You can pass a value-type by reference by using the ref keyword. For more information, see Passing Value-Type Parameters . For a list of built-in value types.
Reference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy. Changes made through this reference will therefore be reflected in the calling method. A reference type is created by using the class keyword as in the following example:
public class SampleRefType
{
public int value;
}
Now, if an object that is based on this type is passed to a method, the object will be passed by reference. For example:
public static void TestRefType()
{
SampleRefType rt = new SampleRefType();
rt.value = 44;
ModifyObject(rt);
Console.WriteLine(rt.value);
}
static void ModifyObject(SampleRefType obj)
{
obj.value = 33;
}
Return Values
Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, the method can return the value by using the return keyword. A statement with the return keyword followed by a value that matches the return type will return that value to the method caller. The return keyword also stops the execution of the method. If the return type is void, a return statement without a value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block. Methods with a non-void return type are required to use the return keyword to return a value. For example, these two methods use the return keyword to return integers:
int result = obj.AddTwoNumbers(1, 2);
result = obj.SquareANumber(result);
// The result is 9.
Console.WriteLine(result)
source: MSDN
It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.
Partial Classes:
There are several situations when splitting a class definition is desirable:
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All 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 part is declared abstract, then the whole type is considered abstract. If any part is declared sealed, then the whole type is considered sealed. If any part declares a base type, then the whole type inherits that class.
All 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 the interfaces listed by all the partial declarations. Any class, struct, or interface members declared in a partial definition are available to all the other parts. The final type is the combination of all the parts at compile time.
The partial modifier is not available on delegate or enumeration declarations.
The following are merged from all the partial-type definitions:
Partial Classes:
There are several situations when splitting a class definition is desirable:
- When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
- 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 it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.
- To split a class definition, use the partial keyword modifier.
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All 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 part is declared abstract, then the whole type is considered abstract. If any part is declared sealed, then the whole type is considered sealed. If any part declares a base type, then the whole type inherits that class.
All 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 the interfaces listed by all the partial declarations. Any class, struct, or interface members declared in a partial definition are available to all the other parts. The final type is the combination of all the parts at compile time.
The partial modifier is not available on delegate or enumeration declarations.
The following are merged from all the partial-type definitions:
- XML comments
- interfaces
- generic-type parameter attributes
- class attributes
- members
A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.
Method Signatures
Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.
abstract class Motorcycle
{
// Anyone can call this.
public void StartEngine() {/* Method statements here */ }
// Only derived classes can call this.
protected void AddGas(int gallons) { /* Method statements here */ }
// Derived classes can override the base class implementation.
public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; }
// Derived classes must implement this.
public abstract double GetTopSpeed();
}
Method Access
Calling a method on an object is like accessing a field. After the object name, add a period, the name of the method, and parentheses. Arguments are listed within the parentheses, and are separated by commas. The methods of the Motorcycle class can therefore be called as in the following example:
class TestMotorcycle : Motorcycle
{
public override double GetTopSpeed()
{
return 108.4;
}
static void Main()
{
TestMotorcycle moto = new TestMotorcycle();
moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);
double speed = moto.GetTopSpeed();
Console.WriteLine("My top speed is {0}", speed);
}
}
Method Parameters vs. Arguments
The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method. For example:
public void Caller()
{
int numA = 4;
// Call with an int variable.
int productA = Square(numA);
int numB = 32;
// Call with another int variable.
int productB = Square(numB);
// Call with an integer literal.
int productC = Square(12);
// Call with an expression that evaulates to int.
productC = Square(productA * 3);
}
int Square(int i)
{
// Store input argument in a local variable.
int input = i;
return input * input;
}
Passing by Reference vs. Passing by Value
By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method. You can pass a value-type by reference by using the ref keyword. For more information, see Passing Value-Type Parameters . For a list of built-in value types.
Reference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy. Changes made through this reference will therefore be reflected in the calling method. A reference type is created by using the class keyword as in the following example:
public class SampleRefType
{
public int value;
}
Now, if an object that is based on this type is passed to a method, the object will be passed by reference. For example:
public static void TestRefType()
{
SampleRefType rt = new SampleRefType();
rt.value = 44;
ModifyObject(rt);
Console.WriteLine(rt.value);
}
static void ModifyObject(SampleRefType obj)
{
obj.value = 33;
}
Return Values
Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, the method can return the value by using the return keyword. A statement with the return keyword followed by a value that matches the return type will return that value to the method caller. The return keyword also stops the execution of the method. If the return type is void, a return statement without a value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block. Methods with a non-void return type are required to use the return keyword to return a value. For example, these two methods use the return keyword to return integers:
int result = obj.AddTwoNumbers(1, 2);
result = obj.SquareANumber(result);
// The result is 9.
Console.WriteLine(result)
source: MSDN
Method Signatures
Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.
abstract class Motorcycle
{
// Anyone can call this.
public void StartEngine() {/* Method statements here */ }
// Only derived classes can call this.
protected void AddGas(int gallons) { /* Method statements here */ }
// Derived classes can override the base class implementation.
public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; }
// Derived classes must implement this.
public abstract double GetTopSpeed();
}
Method Access
Calling a method on an object is like accessing a field. After the object name, add a period, the name of the method, and parentheses. Arguments are listed within the parentheses, and are separated by commas. The methods of the Motorcycle class can therefore be called as in the following example:
class TestMotorcycle : Motorcycle
{
public override double GetTopSpeed()
{
return 108.4;
}
static void Main()
{
TestMotorcycle moto = new TestMotorcycle();
moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);
double speed = moto.GetTopSpeed();
Console.WriteLine("My top speed is {0}", speed);
}
}
Method Parameters vs. Arguments
The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method. For example:
public void Caller()
{
int numA = 4;
// Call with an int variable.
int productA = Square(numA);
int numB = 32;
// Call with another int variable.
int productB = Square(numB);
// Call with an integer literal.
int productC = Square(12);
// Call with an expression that evaulates to int.
productC = Square(productA * 3);
}
int Square(int i)
{
// Store input argument in a local variable.
int input = i;
return input * input;
}
Passing by Reference vs. Passing by Value
By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method. You can pass a value-type by reference by using the ref keyword. For more information, see Passing Value-Type Parameters . For a list of built-in value types.
Reference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy. Changes made through this reference will therefore be reflected in the calling method. A reference type is created by using the class keyword as in the following example:
public class SampleRefType
{
public int value;
}
Now, if an object that is based on this type is passed to a method, the object will be passed by reference. For example:
public static void TestRefType()
{
SampleRefType rt = new SampleRefType();
rt.value = 44;
ModifyObject(rt);
Console.WriteLine(rt.value);
}
static void ModifyObject(SampleRefType obj)
{
obj.value = 33;
}
Return Values
Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, the method can return the value by using the return keyword. A statement with the return keyword followed by a value that matches the return type will return that value to the method caller. The return keyword also stops the execution of the method. If the return type is void, a return statement without a value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block. Methods with a non-void return type are required to use the return keyword to return a value. For example, these two methods use the return keyword to return integers:
int result = obj.AddTwoNumbers(1, 2);
result = obj.SquareANumber(result);
// The result is 9.
Console.WriteLine(result)
source: MSDN
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
{
public Person()
{
}
#region Property
private string _firstName = String.Empty;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}
- Properties enable a class to expose a public way of getting and setting values.
- A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. For more information, see Asymmetric Accessor Accessibility
- The value keyword is used to define the value being assigned by the set accessor.
- Properties that do not implement a set accessor are read only.
{
public Person()
{
}
#region Property
private string _firstName = String.Empty;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}
A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.
A class or struct may have instance fields or static fields or both. Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object. By contrast, a static field belongs to the class itself, and is shared among all instances of that class.
Fields can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the fields. For more information, see Access Modifiers (C# Programming Guide).
A field can optionally be declared static. This makes the field available to callers at any time, even if no instance of the class exists. For more information, see Static Classes and Static Class Members (C# Programming Guide).
A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time. For more information, see Constants (C# Programming Guide).
public class Person
{
public Person()
{
}
#region Property
private int _personID = 0;
public int PersonID
{
get { return _personID; }
set { _personID = value; }
}
private string _firstName = String.Empty;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
private string _middleName = String.Empty;
public string MiddleName
{
get { return _middleName; }
set { _middleName = value; }
}
private string _lastName = String.Empty;
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
private string _gender = String.Empty;
public string Gender
{
get { return _gender; }
set { _gender = value; }
}
private string _dateofbirth = String.Empty;
public string DateOfBirth
{
get { return _dateofbirth; }
set { _dateofbirth = value; }
}
private string _email = String.Empty;
public string Email
{
get { return _email; }
set { _email = value; }
}
private string _primaryPhone = String.Empty;
public string PrimaryPhone
{
get { return _primaryPhone; }
set { _primaryPhone = value; }
}
private string _mobilePhone = String.Empty;
public string MobilePhone
{
get { return _mobilePhone; }
set { _mobilePhone = value; }
}
private string _address = String.Empty;
public string Address
{
get { return _address; }
set { _address = value; }
}
private string _city = String.Empty;
public string City
{
get { return _city; }
set { _city = value; }
}
private string _state = String.Empty;
public string State
{
get { return _state; }
set { _state = value; }
}
private string _zip = String.Empty;
public string Zip
{
get { return _zip; }
set { _zip = value; }
}
private string _country = String.Empty;
public string Country
{
get { return _country; }
set { _country = value; }
}
private string _personImage = String.Empty;
public string PersonImage
{
get { return _personImage; }
set { _personImage = value; }
}
private int _accountStatus = 0;
public int AccountStatus
{
get { return _accountStatus; }
set { _accountStatus = value; }
}
private string _userName = String.Empty;
public string UserName
{
get { return _userName; }
set { _userName = value; }
}
private string _password = String.Empty;
public string Password
{
get { return _password; }
set { _password = value; }
}
private bool _isActive = false;
public bool IsActive
{
get { return _isActive; }
set { _isActive = value; }
}
private bool _isLock = false;
public bool IsLock
{
get { return _isLock; }
set { _isLock = value; }
}
#endregion
}
A class or struct may have instance fields or static fields or both. Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object. By contrast, a static field belongs to the class itself, and is shared among all instances of that class.
Fields can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the fields. For more information, see Access Modifiers (C# Programming Guide).
A field can optionally be declared static. This makes the field available to callers at any time, even if no instance of the class exists. For more information, see Static Classes and Static Class Members (C# Programming Guide).
A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time. For more information, see Constants (C# Programming Guide).
public class Person
{
public Person()
{
}
#region Property
private int _personID = 0;
public int PersonID
{
get { return _personID; }
set { _personID = value; }
}
private string _firstName = String.Empty;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
private string _middleName = String.Empty;
public string MiddleName
{
get { return _middleName; }
set { _middleName = value; }
}
private string _lastName = String.Empty;
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
private string _gender = String.Empty;
public string Gender
{
get { return _gender; }
set { _gender = value; }
}
private string _dateofbirth = String.Empty;
public string DateOfBirth
{
get { return _dateofbirth; }
set { _dateofbirth = value; }
}
private string _email = String.Empty;
public string Email
{
get { return _email; }
set { _email = value; }
}
private string _primaryPhone = String.Empty;
public string PrimaryPhone
{
get { return _primaryPhone; }
set { _primaryPhone = value; }
}
private string _mobilePhone = String.Empty;
public string MobilePhone
{
get { return _mobilePhone; }
set { _mobilePhone = value; }
}
private string _address = String.Empty;
public string Address
{
get { return _address; }
set { _address = value; }
}
private string _city = String.Empty;
public string City
{
get { return _city; }
set { _city = value; }
}
private string _state = String.Empty;
public string State
{
get { return _state; }
set { _state = value; }
}
private string _zip = String.Empty;
public string Zip
{
get { return _zip; }
set { _zip = value; }
}
private string _country = String.Empty;
public string Country
{
get { return _country; }
set { _country = value; }
}
private string _personImage = String.Empty;
public string PersonImage
{
get { return _personImage; }
set { _personImage = value; }
}
private int _accountStatus = 0;
public int AccountStatus
{
get { return _accountStatus; }
set { _accountStatus = value; }
}
private string _userName = String.Empty;
public string UserName
{
get { return _userName; }
set { _userName = value; }
}
private string _password = String.Empty;
public string Password
{
get { return _password; }
set { _password = value; }
}
private bool _isActive = false;
public bool IsActive
{
get { return _isActive; }
set { _isActive = value; }
}
private bool _isLock = false;
public bool IsLock
{
get { return _isLock; }
set { _isLock = value; }
}
#endregion
}
Classes and structs have members that represent their data and behavior. A class's members include all the members declared in the class, along with all members (except constructors and destructors) declared in all classes in its inheritance hierarchy. Private members in base classes are inherited but are not accessible from derived classes.
The following table lists the kinds of members a class or struct may contain:
Fields:
Fields are variables declared at class scope. A field may be a built-in numeric type or an instance of another class. For example, a calendar class may have a field that contains the current date.
Constants:
Constants are fields or properties whose value is set at compile time and cannot be changed.
Properties:
Properties are methods on a class that are accessed as if they were fields on that class. A property can provide protection for a class field to keep it from being changed without the knowledge of the object.
Methods:
Methods define the actions that a class can perform. Methods can take parameters that provide input data, and can return output data through parameters. Methods can also return a value directly, without using a parameter.
Events:
Events provide notifications about occurrences, such as button clicks or the successful completion of a method, to other objects. Events are defined and triggered by using delegates. For more information, see Events and Delegates.
Operators:
Overloaded operators are considered class members. When you overload an operator, you define it as a public static method in a class. The predefined operators (+, *, <, and so on) are not considered members. For more information, see Overloadable Operators .
Indexers:
Indexers enable an object to be indexed in a manner similar to arrays.
Constructors:
Constructors are methods that are called when the object is first created. They are often used to initialize the data of an object.
Destructors:
Destructors are used very rarely in C#. They are methods that are called by the runtime execution engine when the object is about to be removed from memory. They are generally used to make sure that any resources which must be released are handled appropriately.
Nested Types:
Nested types are types declared within another type. Nested types are often used to describe objects that are used only by the types that contain them.
The following table lists the kinds of members a class or struct may contain:
Fields:
Fields are variables declared at class scope. A field may be a built-in numeric type or an instance of another class. For example, a calendar class may have a field that contains the current date.
Constants:
Constants are fields or properties whose value is set at compile time and cannot be changed.
Properties:
Properties are methods on a class that are accessed as if they were fields on that class. A property can provide protection for a class field to keep it from being changed without the knowledge of the object.
Methods:
Methods define the actions that a class can perform. Methods can take parameters that provide input data, and can return output data through parameters. Methods can also return a value directly, without using a parameter.
Events:
Events provide notifications about occurrences, such as button clicks or the successful completion of a method, to other objects. Events are defined and triggered by using delegates. For more information, see Events and Delegates.
Operators:
Overloaded operators are considered class members. When you overload an operator, you define it as a public static method in a class. The predefined operators (+, *, <, and so on) are not considered members. For more information, see Overloadable Operators .
Indexers:
Indexers enable an object to be indexed in a manner similar to arrays.
Constructors:
Constructors are methods that are called when the object is first created. They are often used to initialize the data of an object.
Destructors:
Destructors are used very rarely in C#. They are methods that are called by the runtime execution engine when the object is about to be removed from memory. They are generally used to make sure that any resources which must be released are handled appropriately.
Nested Types:
Nested types are types declared within another type. Nested types are often used to describe objects that are used only by the types that contain them.
Declare static class members by using the static keyword before the return type of the member.
static class:
WebUtilityClass.MethodA();
As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application.
static class:
- Contains only static members.
- Cannot be instantiated.
- Is sealed.
- Cannot contain Instance Constructors.
WebUtilityClass.MethodA();
As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application.
Classes can be declared as abstract by putting the keyword abstract before the class definition. For example:
public abstract class A
{
// Class members here.
}
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.
Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example:
public abstract class A
{
public abstract void DoWork(int i);
}
Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. For example:
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.
public abstract class A
{
// Class members here.
}
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.
Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example:
public abstract class A
{
public abstract void DoWork(int i);
}
Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. For example:
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.
Classes can be declared as sealed by putting the keyword sealed before the class definition. For example:
public sealed class D
{
// Class members here.
}
A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.
A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration.
public class D : C
{
public sealed override void DoWork() { }
}
public sealed class D
{
// Class members here.
}
A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.
A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration.
public class D : C
{
public sealed override void DoWork() { }
}
Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance.
At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.
Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.
Virtual methods enable you to work with groups of related objects in a uniform way. For example, suppose you have a drawing application that enables a user to create various kinds of shapes on a drawing surface. You do not know at compile time which specific types of shapes the user will create. However, the application has to keep track of all the various types of shapes that are created, and it has to update them in response to user mouse actions. You can use polymorphism to solve this problem in two basic steps:
Create a class hierarchy in which each specific shape class derives from a common base class.
Use a virtual method to invoke the appropriate method on any derived class through a single call to the base class method.
First, create a base class called Shape, and derived classes such as Rectangle, Circle, and Triangle. Give the Shape class a virtual method called Draw, and override it in each derived class to draw the particular shape that the class represents. Create a List object and add a Circle, Triangle and Rectangle to it. To update the drawing surface, use a foreach loop to iterate through the list and call the Draw method on each Shape object in the list. Even though each object in the list has a declared type of Shape, it is the run-time type (the overridden version of the method in each derived class) that will be invoked.
public class Shape
{
// A few example members
public int X { get; private set; }
public int Y { get; private set; }
public int Height { get; set; }
public int Width { get; set; }
// Virtual method
public virtual void Draw()
{
Console.WriteLine("Performing base class drawing tasks");
}
}
class Circle : Shape
{
public override void Draw()
{
// Code to draw a circle...
Console.WriteLine("Drawing a circle");
base.Draw();
}
}
class Rectangle : Shape
{
public override void Draw()
{
// Code to draw a rectangle...
Console.WriteLine("Drawing a rectangle");
base.Draw();
}
}
class Triangle : Shape
{
public override void Draw()
{
// Code to draw a triangle...
Console.WriteLine("Drawing a triangle");
base.Draw();
}
}
class Program
{
static void Main(string[] args)
{
// Polymorphism at work #1: a Rectangle, Triangle and Circle
// can all be used whereever a Shape is expected. No cast is
// required because an implicit conversion exists from a derived
// class to its base class.
System.Collections.Generic.List shapes = new System.Collections.Generic.List();
shapes.Add(new Rectangle());
shapes.Add(new Triangle());
shapes.Add(new Circle());
// Polymorphism at work #2: the virtual method Draw is
// invoked on each of the derived classes, not the base class.
foreach (Shape s in shapes)
{
s.Draw();
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
Drawing a rectangle
Performing base class drawing tasks
Drawing a triangle
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks
*/
In C#, every type is polymorphic because all types, including user-defined types, inherit from Object.
At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.
Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.
Virtual methods enable you to work with groups of related objects in a uniform way. For example, suppose you have a drawing application that enables a user to create various kinds of shapes on a drawing surface. You do not know at compile time which specific types of shapes the user will create. However, the application has to keep track of all the various types of shapes that are created, and it has to update them in response to user mouse actions. You can use polymorphism to solve this problem in two basic steps:
Create a class hierarchy in which each specific shape class derives from a common base class.
Use a virtual method to invoke the appropriate method on any derived class through a single call to the base class method.
First, create a base class called Shape, and derived classes such as Rectangle, Circle, and Triangle. Give the Shape class a virtual method called Draw, and override it in each derived class to draw the particular shape that the class represents. Create a List
public class Shape
{
// A few example members
public int X { get; private set; }
public int Y { get; private set; }
public int Height { get; set; }
public int Width { get; set; }
// Virtual method
public virtual void Draw()
{
Console.WriteLine("Performing base class drawing tasks");
}
}
class Circle : Shape
{
public override void Draw()
{
// Code to draw a circle...
Console.WriteLine("Drawing a circle");
base.Draw();
}
}
class Rectangle : Shape
{
public override void Draw()
{
// Code to draw a rectangle...
Console.WriteLine("Drawing a rectangle");
base.Draw();
}
}
class Triangle : Shape
{
public override void Draw()
{
// Code to draw a triangle...
Console.WriteLine("Drawing a triangle");
base.Draw();
}
}
class Program
{
static void Main(string[] args)
{
// Polymorphism at work #1: a Rectangle, Triangle and Circle
// can all be used whereever a Shape is expected. No cast is
// required because an implicit conversion exists from a derived
// class to its base class.
System.Collections.Generic.List
shapes.Add(new Rectangle());
shapes.Add(new Triangle());
shapes.Add(new Circle());
// Polymorphism at work #2: the virtual method Draw is
// invoked on each of the derived classes, not the base class.
foreach (Shape s in shapes)
{
s.Draw();
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
Drawing a rectangle
Performing base class drawing tasks
Drawing a triangle
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks
*/
In C#, every type is polymorphic because all types, including user-defined types, inherit from Object.
A derived class has access to the public, protected, internal, and protected internal members of a base class. Even though a derived class inherits the private members of a base class, it cannot access those members. However, all those private members are still present in the derived class and can do the same work they would do in the base class itself. For example, suppose that a protected base class method accesses a private field. That field has to be present in the derived class in order for the inherited base class method to work properly.
An interface is a reference type that is somewhat similar to an abstract base class that consists of only abstract members. When a class derives from an interface, it must provide an implementation for all the members of the interface. A class can implement multiple interfaces even though it can derive from only a single direct base class.
Interfaces are used to define specific capabilities for classes that do not necessarily have an "is a" relationship. For example, the IEquatable[`1] interface can be implemented by any class or struct that has to enable client code to determine whether two objects of the type are equivalent (however the type defines equivalence). IEquatable<(Of <(T>)>) does not imply the same kind of "is a" relationship that exists between a base class and a derived class.
Interfaces are used to define specific capabilities for classes that do not necessarily have an "is a" relationship. For example, the IEquatable[`1] interface can be implemented by any class or struct that has to enable client code to determine whether two objects of the type are equivalent (however the type defines equivalence). IEquatable<(Of <(T>)>) does not imply the same kind of "is a" relationship that exists between a base class and a derived class.
Declare a class as abstract if you want to prevent direct instantiation by means of the new keyword. If you do this, the class can be used only if a new class is derived from it. An abstract class can contain one or more method signatures that themselves are declared as abstract. These signatures specify the parameters and return value but have no implementation.
An abstract class does not have to contain abstract members; however, if a class does contain an abstract member, the class itself must be declared as abstract. Derived classes that are not abstract themselves must provide the implementation for any abstract methods from an abstract base class.
An abstract class does not have to contain abstract members; however, if a class does contain an abstract member, the class itself must be declared as abstract. Derived classes that are not abstract themselves must provide the implementation for any abstract methods from an abstract base class.
When a base class declares a method as virtual, a derived class can override the method with its own implementation. If a base class declares a member as abstract, that method must be overridden in any non-abstract class that directly inherits from that class. If a derived class is itself abstract, then it inherit abstract members without implementing them. Abstract and virtual members are the basis for polymorphism, which is the second primary characteristic of object-oriented programming.
Structs are defined by using the struct keyword.
public struct PersonAddress
{
// Fields, properties, methods and events go here...
}
Structs share most of the same syntax as classes, although structs are more limited than classes:
public struct PersonAddress
{
// Fields, properties, methods and events go here...
}
Structs share most of the same syntax as classes, although structs are more limited than classes:
- 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 without parameters) or a destructor.
- Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary
.
- Structs are value types and classes are reference types.
- Unlike classes, structs can be instantiated without using a new operator.
- Structs can declare constructors that have 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.
- A struct can be used as a nullable type and can be assigned a null value.
A class or struct definition is like a blueprint that specifies what the type can do. An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object. In an object-oriented language such as C#, a typical program consists of multiple objects interacting dynamically.
A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable.
Declaring Classes
Classes are declared by using the class keyword.
public class Person
{
//Fields, properties, methods and events go here...
}
The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members.
Creating Objects
Although they are sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class.
Objects can be created by using the new keyword followed by the name of the class that the object will be based on, like this:
Person object1 = new Person();
Class Inheritance
Inheritance is accomplished by using a derivation, which means a class is declared by using a base class from which it inherits data and behavior. A base class is specified by appending a colon and the name of the base class following the derived class name, like this:
public class Office : Employee
{
// Employee fields, properties, methods and events are inherited
// New Office fields, properties, methods and events go here...
}
A class can be declared abstract. An abstract class contains abstract methods that have a signature definition but no implementation. Abstract classes cannot be instantiated. They can only be used through derived classes that implement the abstract methods. By constrast, a sealed class does not allow other classes to derive from it.
Declaring Classes
Classes are declared by using the class keyword.
public class Person
{
//Fields, properties, methods and events go here...
}
The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members.
Creating Objects
Although they are sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class.
Objects can be created by using the new keyword followed by the name of the class that the object will be based on, like this:
Person object1 = new Person();
Class Inheritance
Inheritance is accomplished by using a derivation, which means a class is declared by using a base class from which it inherits data and behavior. A base class is specified by appending a colon and the name of the base class following the derived class name, like this:
public class Office : Employee
{
// Employee fields, properties, methods and events are inherited
// New Office fields, properties, methods and events go here...
}
A class can be declared abstract. An abstract class contains abstract methods that have a signature definition but no implementation. Abstract classes cannot be instantiated. They can only be used through derived classes that implement the abstract methods. By constrast, a sealed class does not allow other classes to derive from it.