Any class in an object-oriented language has method and property members. These are the places where the actual business logic or functionality is written and executed.
C# Methods:
Method is object-oriented item of any language. All C# programs are constructed from a number of classes and almost all the classes will contain methods. A class when instantiated is called an object. Object-oriented concepts of programming say that the data members of each object represent its state and methods represent the object behavior.
Method Signature in C#:
Each method is declared as follows:
Return-type methodname ( Parameterslist );
For better understanding of methods let consider following example. We have a class Man. It can have many fields like that:
public class Man
{
public Man(){}
private int m_old;
private string m_name;
public string WhatIsYourName()
{
Console.WriteLine(m_name);
return m_name;
}
public string HowOldAreYou()
{
Console.WriteLine(m_old.ToString());
return m_old;
}
}
{
public Man(){}
private int m_old;
private string m_name;
public string WhatIsYourName()
{
Console.WriteLine(m_name);
return m_name;
}
public string HowOldAreYou()
{
Console.WriteLine(m_old.ToString());
return m_old;
}
}
The private members m_old and m_name define some state of objects that can be created as instances of our class. Also the class Man has two methods, which serve some of our requests. Method string WhatIsYourName() writes current object's name to the console and returns it, and the second one similar to first return age of man and also writes an output to the console.
The return type in the example above returns strings, which is an in-built data type. The methods can also return any generic C# type or any custom types created by us.
Passing Parameters to Methods in C#:
The input parameters can be passed in two ways.
· Value type
· Reference type.
If parameters are passed as value types a new copy of it will be created and passed inside the function. If they are created as reference types, only the address of the parameters will be passed.
See next example:
public int CalculateBirthYear(int year)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
If input parameter pass as reference type it must use keyword ref, in that way we operate with the same cell in memory. That's mean it can be changed inside any method. A small example for a parameter passed by reference is:
public int CalculateBirthYear(ref int year)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
Now, the function CalculateBirthYear can even modify the value of year as it is passed by reference.
Output Parameters in Methods:
The return values in any function will be enough for any one if only one value is needed. But in case a function is required to return more than one value, then output parameters are the norm. This is not supported in C++ though it can be achieved by using some programming tricks. In C# the output parameter is declared with the keyword out before the data type. A typical example is as follows.
public void CalculateBirthYear(ref int year, out int birthyear)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
birthyear = b;
return;
}
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
birthyear = b;
return;
}
Strictly speaking there is no difference between ref and out parameters. The only difference is that the ref input parameters need an input value and the out parameters don't.
class Test
{
static void SplitPath(string path, out string dir, out string name) {
int i = path.Length;
while (i > 0) {
char ch = path[i – 1];
if (ch == '\\' || ch == '/' || ch == ':') break;
i--;
}
dir = path.Substring(0, i);
name = path.Substring(i);
}
static void Main () {
string dir, name;
SplitPath("c:\\Windows\\System\\hello.txt", out dir, out name);
Console.WriteLine(dir);
Console.WriteLine(name);
}
}
The example produces the output
hello.txt
Note that the dir and name variables can be unassigned before they are passed to SplitPath, and that they are considered definitely assigned following the call.
Variable arguments/Parameter Array in C#:
The C# language supports variable arguments through a keyword called params. A typical example for the declaration of a function with variable argument signature is as follows.
Public void functionName(int a, params int[] varParam);
Parameter arrays allow a variable number of arguments to be passed into a function member. The definition of the parameter has to include the params modifier, but the use of the parameter has no such keyword. A parameter array has to come at the end of the list of parameters, and must be a single-dimensional array. When using the function member, any number of parameters (including none) may appear in the invocation, so long as the parameters are each compatible with the type of the parameter array. Alternatively, a single array may be passed, in which case the parameter acts just as a normal value parameter. For example:
void ShowNumbers (params int[] numbers)
{
foreach (int x in numbers)
{
Console.Write (x+" ");
}
Console.WriteLine();
}
...
int[] x = {1, 2, 3};
ShowNumbers (x);
ShowNumbers (4, 5);
Method Overloading in C#:
A method is considered to be an overloaded method, if it has two or more signatures for the same method name. These methods will contain different parameters but the same return types.
A simple example for an overloaded methods are:
Public void functionName(int a, params int[] varParam);
Public void functionName(int a);
Public void functionName(int a);
Property in C#:
Property ' it is a special method that can return a current object's state or set it. Simple syntax of properties can see in the following example:
public int Old
{
get {return m_old;}
set {m_old = value;}
}
public string Name
{
get {return m_name;}
}
{
get {return m_old;}
set {m_old = value;}
}
public string Name
{
get {return m_name;}
}
Here are two types of properties. A first one can set or get field of class named m_old, and the second is read only. That's mean it can only get current object's state.
The significance of these properties is its usability. These properties need not be called with any function names like objectname.get or objectname.set etc., But they can be directly assigned the values or retrieve the values.
And at least few words about access modifiers of methods and properties.
Class Modifiers
The class is one of the two basic encapsulation constructs in C# (the other being the struct). Every executable statement must be placed inside a class or struct. Classes define reference types that are the basic building blocks of C# programs, and they are the architectural blueprint for the "objects" in OOP.
A class can be...
abstract: An instance of the class cannot be created. Usually this means the class is intended to serve as a base class.
abstract class A
{
public abstract void F();
}
abstract class B: A
{
public void G() {}
}
class C: B
{
public override void F() {
// actual implementation of F
}
}
sealed: The class cannot serve as a base class for another class (it can't be derived from). A class cannot be both abstract and sealed.
using System;
sealed class MyClass
{
public int x;
public int y;
}
class MainClass
{
public static void Main ()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
In the preceding example, if you attempt to inherit from the sealed class by using a statement like this:
class MyDerivedC: MyClass {} // Error
You will get the error message:
'MyDerivedC' cannot inherit from sealed class 'MyBaseC'.
internal: The class is only accessible from other classes in the same assembly. This is the default access for non-nested types. If no modifier is specified, the class has internal access.
new: Used only with nested classes. "New" indicates that the class hides an inherited member of the same name.
private: A nested class that can only be accessed inside the class in which it is defined.
public: Instances of this class are available to any class that wants to access it.
Constructor
A class defines data members, methods and nested types. A constructor is a special method that is normally used to initialize the data members of a class, and its name is always the same as the name of the class. Constructors have no return value, and any number of constructors can be defined within a class. If no constructor is defined, the C# compiler provides a default constructor having no parameters
Methods
Methods are always defined within the bounds of a class or struct. Methods can be instance (called as an instance of the type within which the method is defined) or static, where the method is associated with the type itself. Methods can be declared as virtual, abstract , or sealed. Methods can be overloaded, overridden.
Access Modifiers
Access modifiers are specified as part of the method declaration syntax and can be:
internal
private
protected
protected internal
public
private
protected
protected internal
public
If no modifier is specified, the method is given private access.
virtual methods can be overriden by a derived class using the override keyword.
abstract methods must be overriden in a derived class. If any method of a class is abstract, the entire class must be declared as abstract.
sealed methods are methods that override an inherited virtual method having the same signature. When a method is sealed, it cannot be overriden in a derived class.
In C# a method can't be declared as sealed. However when we override a method in a derived class, we can declare the overrided method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.
using System;
class MyClass1
{
public int x;
public int y;
public virtual void Method()
{
Console.WriteLine("virtual method");
}
}
class MyClass : MyClass1
{
public override sealed void Method()
{
Console.WriteLine("sealed method");
}
}
class MainClass
{
public static void Main ()
{
MyClass1 mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
mC.Method();
}
}
Method Access Modifiers
public indicates the method is freely accessible inside and outside of the class in which it is defined.
// protected_public.cs
// Public access
using System;
class MyClass1
{
public int x;
public int y;
}
class MyClass2
{
public static void Main ()
{
MyClass1 mC = new MyClass1();
// Direct access to public members:
mC.x = 10;
mC.y = 15;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
internal means the method is only accessible to types defined in the same assembly. Or in other words The internal keyword is an access modifier for types and type members. Internal members are accessible only within files in the same assembly.
protected The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. For example, consider the following code segment:
class A
{
protected int x = 123;
}
class B : A
{
void F()
{
A a = new A();
B b = new B();
a.x = 10; // Error
b.x = 10; // OK
}
}
protected internal means the method is accessible to types defined in the same assembly or to types in a derived assembly.
private The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared.
Method Overriding
Method overriding is a feature that allows you to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance using the base class reference.
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class Demo
{
public static void Main ()
{
BC b;
b = new BC();
b.Display();
}
}
OutPut
BC::Display
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class Demo
{
public static void Main ()
{
BC b;
b = new BC();
b.Display();
b = new DC();
b.Display();
}
}
OutPut
BC::Display
BC::Display
class BC
{
public virtual void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class Demo
{
public static void Main ()
{
BC b;
b = new BC();
b.Display();
b = new DC();
b.Display();
}
}
OutPut
BC::Display
DC::Display
No comments:
Post a Comment