You are on page 1of 35

Abstract class

Abstract classes are one of the essential behaviors provided by .NET Commonly, you would like to make classes that only represent base classes, and dont want anyone to create objects of these class types. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'. An abstract class means that, no object of this class can be instantiated, but can make derivations of this. An example of an abstract class declaration is: abstract class absClass { }

The abstract keyword enables you to create classes and class members solely for the purpose of inheritanceto define features of derived.

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class. An example of an abstract method: Abstract class absClass { Public abstract void Method(); }

abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. abstract class absClass { public void NonAbstractMethod() { Console.WriteLine("NonAbstract Method"); } }

using System; namespace abstractSample { abstract class absClass { public int AddTwoNumbers(int Num1, int Num2) { return Num1 + Num2; }

public abstract int MultiplyTwoNumbers(int Num1, int Num2); } class absDerived:absClass { static void Main(string[] args) { absDerived calculate = new absDerived();

int added = calculate.AddTwoNumbers(10,20); int multiplied = calculate.MultiplyTwoNumbers(10,20); Console.WriteLine("Added : {0}, Multiplied : {1}", added, multiplied); } public override int MultiplyTwoNumbers(int Num1, intNum2) { return Num1 * Num2; } } }

Abstract class abs Class contains two methods AddTwoNumbers and, MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation. The class absDerived is derived from absClass the MultiplyTwoNumbers is implemented on absDerived. and

in the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class

abstract class absClass1 { public abstract int AddTwoNumbers(int Num1, int Num2); public abstract int MultiplyTwoNumbers(int Num1, int Num2); } abstract class absClass2:absClass1 { public override int AddTwoNumbers(int Num1, int Num2) { return Num1+Num2;

} } class absDerived:absClass2 {

public override int MultiplyTwoNumbers(int Num1, int Num2) { return Num1*Num2; } }

Static class
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. As there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example: UtilityClass.MethodA();

in the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations, (Math class). That is, you apply the members of the class by specifying the class name and the method name, as shown in the following example. double dub = -3.14; Console.WriteLine(Math.Abs(dub)); Console.WriteLine(Math.Floor(dub)); // Output: // 3.14 // -4

A non-static class can contain static methods also. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.

Object Class
The object class is the ultimate base class of every type. As the ultimate base class that all other types directly or indirectly derive from, the object class .

The Object Class


All classes in C# are derived from the Object class if a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class The Object class is therefore the ultimate root of all class hierarchies The Object class defines methods that will be shared by all objects in C#, e.g., ToString: converts an object to a string representation Equals: checks if two objects are the same GetType: returns the type of a type of object A class can override a method defined in Object to have a 15 different behavior, e.g.,

The Equals method of the object class provides a default implementation that compares two reference type objects for reference equality. Reference equality occurs when two reference type objects refer to the same object. An example is the string class, which Equals to ensure that two strings are compared by the value of their strings. Value types are compared for bitwise equality.

The GetType Method


GetType is the basis for using reflection in .NET. It returns a Type object, describing the object it was called on. The GetType method is also useful if you get an object at runtime and you don't know what it's type is. You can use the returned Type object to figure out what to do with the object.

Value vs. reference types


C# separates data types into two categories Value types:
variable represents a value ("bits")
int i; i = 10;
10

Reference types:

How do you know which types are which?


primitive types like bool, int and double are values remainder are reference types
int Customer i; c1, c2;

i = 23; c1 = null; c2 = new Customer();

All primitive types such as int are called value types. When you declare an int variable, compiler allocates a block of memory big enough to hold an integer. A statement that assigns a value (such as 42) to the int causes the value to be copied to this block of memory. Class types, are handled differently. When you declare a Class variable, the compiler does not allocates a block of memory big enough to hold a Class variable all it does is allot a small piece of memory that can potentially hold the address of (or a reference to) another block of memory containing a Class. The memory for the Class object itself is only allocated when the new keyword is used to create the object.

This demonstrates that value types are so called because they hold values directly. Reference types (such as classes) hold references to blocks of memory. int i = 42;// declare and initialize i int copyi = i;// copyi contains a copy of the data in i i++;// incrementing i has no effect on copyi. When you declare c as a Circle class, c can refer to a Circle object. If you declare refc as another Circle, it can also refer to a Circle object. If you choose to initialize or assign refc to c, refc will refer to the same Circle object that c does; there is only one Circle object, and refc and c both refer to it.

Boxing and Unboxing


When necessary, C# will auto-convert value <==> object
value ==> object is called "boxing" object ==> value is called "unboxing"
int i, j; object obj; i = 32; obj = i; i = 19; j = (int) obj;

// boxed copy! // unboxed!

Working with reference types


Creating, assigning, and comparing:
Customer string c1, c2, c3; s1, s2;

c1 = new Customer("joe hummel", 36259); c2 = new Customer("marybeth lore", 55298); c3 = null; // c3 references no object
c3 = c1;
// c3 now references same obj as c1 // do I ref an object? // compares references // compares objects

if (c1 == null) ... if (c1 == c2) ... if (c1.Equals(c2)) ... if (s1 == s2) ...

// exception: == overloaded to // compare string data

Use of ref and out in function parameters


namespace ConsoleApplication48 { class Program { static void Main(string[] args) { int i = 100; yyy a = new yyy(); //Console.WriteLine(i); //a.abc(out i);

a.abc(ref i); Console.WriteLine(i); }

} class yyy { public void abc(ref int i ) { // i = 10; Console.WriteLine(i); i = 10; } }

Structure and Classes


Structs are similar to classes in that they represent data structures that can contain data members and function members. A struct type is a value type that is typically used to encapsulate small groups of related variables, However, unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly contains the data of the struct, whereas a variable of a class type contains a reference to the data, the latter known as an object. Assignment to a variable of a struct type creates a copy of the value being assigned

public struct Book { public int price; public string title; public string author; }

When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized. A struct is not permitted to declare a parameter less constructor

Structs are particularly useful for small data structures . Key to these data structures is that they have few data members, that they do not require use of inheritance or referential identity, where assignment copies the value instead of the reference.

using System; public struct Point { public int x, y; public Point(int p1, int p2) { x = p1; y = p2; } } class MainClass { public static void Main() { Point myPoint = new Point(); Point yourPoint = new Point(10,10); Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y); Console.WriteLine("x = {0}, y = {1}", yourPoint.x, yourPoint.y); } }

using System; public struct Point { public int x, y; public Point(int x1, int y1) { x = x1; y = y1; } } class MainClass { public static void Main() { Point myPoint; myPoint.x = 10; myPoint.y = 20; Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y); } } Output My Point: x = 10, y = 20

Use of read and write property


namespace MyProperty { class Person { string MyName = ""; int MyAge = 0; // Declare a Name property of type string: public string Name { get { return MyName; }

set { MyName = value; } } // Declare an Age property of type int: public int Age { get { return MyAge; }

set { MyAge = value; }

}
public static void Main()

{
// Create a new Person object: Person person = new Person(); person.Age = 20; person.Name="anu"; Console.WriteLine("age={0},name={1}",person.Age, person.Name);

You might also like