CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use...

31
UNIT III - OBJECT-ORIENTED CONCEPTS IN C# Controlling access to class members - Passing references to methods - Use ref and out parameters - Use a variable number of arguments - Return objects - Method Overloading - Overload Constructors - Object initializes The Main() method Recursion - understanding static - Static classes -Operator Overloading - Indexers and Properties. CLASSES When you define a class, you define a blueprint for a data type. This does not actually define any data, but it does define what the class name means. That is, what an object of the class consists of and what operations can be performed on that object. Objects are instances of a class. The methods and variables that constitute a class are called members of the class. Note: Access specifiers specify the access rules for the members as well as the class itself. If not mentioned, then the default access specifier for a class type is internal. Default access for the members is private. Data type specifies the type of variable, and return type specifies the data type of the data the method returns, if any. To access the class members, you use the dot (.) operator. The dot operator links the name of an object with the name of a member. Example using System; namespace BoxApplication { class Box { public double length; // Length of a box public double breadth; // Breadth of a box public double height; } // Height of a box class Boxtester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); // Declare Box2 of type Box

Transcript of CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use...

Page 1: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

UNIT III - OBJECT-ORIENTED CONCEPTS IN C#

Controlling access to class members - Passing references to methods - Use ref and out

parameters - Use a variable number of arguments - Return objects - Method Overloading -

Overload Constructors - Object initializes The Main() method – Recursion - understanding static

- Static classes -Operator Overloading - Indexers and Properties.

CLASSES

When you define a class, you define a blueprint for a data type. This does not actually define any

data, but it does define what the class name means. That is, what an object of the class consists of

and what operations can be performed on that object. Objects are instances of a class. The

methods and variables that constitute a class are called members of the class.

Note:

✓ Access specifiers specify the access rules for the members as well as the class itself. If not

mentioned, then the default access specifier for a class type is internal. Default access for

the members is private.

✓ Data type specifies the type of variable, and return type specifies the data type of the data

the method returns, if any.

✓ To access the class members, you use the dot (.) operator.

✓ The dot operator links the name of an object with the name of a member.

Example

using System;

namespace BoxApplication

{ class Box

{ public double length; // Length of a box

public double breadth; // Breadth of a box

public double height; } // Height of a box

class Boxtester

{ static void Main(string[] args)

{ Box Box1 = new Box(); // Declare Box1 of type Box

Box Box2 = new Box(); // Declare Box2 of type Box

Page 2: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

double volume = 0.0; // Store the volume of a box here

Box1.height = 5.0;

Box1.length = 6.0;

Box1.breadth = 7.0;

Box2.height = 10.0; // box 2 specification

Box2.length = 12.0;

Box2.breadth = 13.0;

volume = Box1.height * Box1.length * Box1.breadth; // volume of box 1

Console.WriteLine("Volume of Box1 : {0}", volume);

volume = Box2.height * Box2.length * Box2.breadth; // volume of box 2

Console.WriteLine("Volume of Box2 : {0}", volume);

Console.ReadKey();

} } }

Output

Volume of Box1 : 210

Volume of Box2 : 1560

METHODS

A method is a group of statements that together perform a task. Every C# program has at least

one class with a method named Main.

To use a method, you need to:

✓ Define the method

✓ Call the method

Defining Methods in C#

When you define a method, you basically declare the elements of its structure.

The syntax for defining a method in C# is as follows:

Page 3: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

<Access Specifier><Return Type><Method Name> (Parameter List)

{

Method Body

}

Following are the various elements of a method:

✓ Access Specifier: This determines the visibility of a variable or a method from another

class.

✓ Return type: A method may return a value. The return type is the data type of the value

the method returns. If the method is not returning any values, then the return type is void.

✓ Method name: Method name is a unique identifier and it is case sensitive. It cannot be

same as any other identifier declared in the class.

o Parameter list: Enclosed between parentheses, the parameters are used to pass and

receive data from a method. The parameter list refers to the type, order, and

number of the parameters of a method. Parameters are optional; that is, a method

may contain no parameters.

o Method body: This contains the set of instructions needed to complete the

required activity.

Example

Following code snippet shows a function FindMax that takes two integer values and returns the

larger of the two. It has public access specifier, so it can be accessed from outside the class using

an instance of the class.

Calling Methods in C#

using System;

namespace CalculatorApplication

{class NumberManipulator

{public int FindMax(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

Page 4: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

else

result = num2;

return result;

}

static void Main(string[] args)

{

int a = 100;

int b = 200;

int ret;

NumberManipulator n = new NumberManipulator();

ret = n.FindMax(a, b); //calling the FindMax method

Console.WriteLine("Max value is : {0}", ret );

Console.ReadLine();

} }

Output

Max value is : 200

Recursive Method Call

A method can call itself. This is known as recursion. Following is an example that calculates

factorial for a given number using a recursive function:

using System;

namespace CalculatorApplication

{ class NumberManipulator

{ public int factorial(int num)

{ int result;

Page 5: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

if (num == 1)

{ return 1; }

else

{ result = factorial(num - 1) * num;

return result; } }

static void Main(string[] args)

{ NumberManipulator n = new NumberManipulator();

Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6)); //calling the factorial method

Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));

Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));

Console.ReadLine();

} } }

Output

Factorial of 6 is: 720

Factorial of 7 is: 5040

Factorial of 8 is: 40320

Passing Parameters to a Method

When method with parameters is called, you need to pass the parameters to the method. There

are three ways that parameters can be passed to a method:

Mechanism Description

Value parameters This method copies the actual value of an argument into the

formal parameter of the function. In this case, changes made to

the parameter inside the function have no effect on the

argument.

Reference parameters This method copies the reference to the memory location of an

argument into the formal parameter. This means that changes

made to the parameter affect the argument.

Output parameters This method helps in returning more than one value.

Page 6: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Passing Parameters by Value

This is the default mechanism for passing parameters to a method. In this mechanism, when a

method is called, a new storage location is created for each value parameter.

The values of the actual parameters are copied into them. Hence, the changes made to the

parameter inside the method have no effect on the argument. The following example

demonstrates the concept:

using System;

namespace CalculatorApplication

{ class NumberManipulator

{ public void swap(int x, int y)

{ int temp;

temp = x; /* save the value of x */

x = y; /* put y into x */

y = temp; /* put temp into y */

}

static void Main(string[] args)

{ NumberManipulator n = new NumberManipulator();

int a = 100; /* local variable definition */

int b = 200;

Console.WriteLine("Before swap, value of a : {0}", a);

Console.WriteLine("Before swap, value of b : {0}", b);

n.swap(a, b); /* calling a function to swap the values */

Console.WriteLine("After swap, value of a : {0}", a);

Console.WriteLine("After swap, value of b : {0}", b);

Console.ReadLine();

} } }

Page 7: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Output

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :100

After swap, value of b :200

Passing Parameters by Reference

A reference parameter is a reference to a memory location of a variable. When you pass

parameters by reference, unlike value parameters, a new storage location is not created for these

parameters. The reference parameters represent the same memory location as the actual

parameters that are supplied to the method.

using System;

namespace CalculatorApplication

{ class NumberManipulator

{ public void swap(ref int x, ref int y)

{ int temp;

temp = x;

x = y;

y = temp;

}

static void Main(string[] args)

{

NumberManipulator n = new NumberManipulator();

int a = 100;

int b = 200;

Console.WriteLine("Before swap, value of a : {0}", a);

Console.WriteLine("Before swap, value of b : {0}", b);

Page 8: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

n.swap(ref a, ref b);

Console.WriteLine("After swap, value of a : {0}", a);

Console.WriteLine("After swap, value of b : {0}", b);

Console.ReadLine();

} } }

Output

Before swap, value of a: 100

Before swap, value of b: 200

After swap, value of a: 200

After swap, value of b: 100

Passing Parameters by Output

A return statement can be used for returning only one value from a function. However, using

output parameters, you can return two values from a function. Output parameters are similar to

reference parameters, except that they transfer data out of the method rather than into it.

using System;

namespace CalculatorApplication

{

class NumberManipulator

{

public void getValue(out int x )

{ int temp = 5;

x = temp; }

static void Main(string[] args)

{

NumberManipulator n = new NumberManipulator();

int a = 100;

Page 9: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Console.WriteLine("Before method call, value of a : {0}", a);

n.getValue(out a); /* calling a function to get the value */

Console.WriteLine("After method call, value of a : {0}", a);

Console.ReadLine();

} } }

Output

Before method call, value of a: 100

After method call, value of a: 5

Out Parameter With Examples in C#

The out is a keyword in C# which is used for the passing the arguments to methods as a

reference type. It is generally used when a method returns multiple values.

Important Points:

• It is similar to ref keyword. But the main difference between ref and out keyword is that

ref needs that the variable must be initialized before it passed to the method. But out

parameter doesn’t require the variables to be initialized before it passed to the method.

But before it returns a value to the calling method, the variable must be initialized in the

called method.

• It is also similar to the in keyword but the in keyword does not allow the method that

called to change the argument value but ref allows.

• For using out keyword as parameter both the method definition and calling method must

use the out keyword explicitly.

• The out parameters are not allowed to use in asynchronous methods.

• The out parameters are not allowed to use in iterator methods.

• There can be more than one out parameter in a method.

• At the time of method call, out parameter can be declared inline. But the inline out

parameters can be accessed in the same block of code where it calls.

• Method overloading can also be done using out parameters.

• Properties cannot be passed as out parameters as these are not variables.

• Up to C# 6.0, a user first declares the variable then it can only pass as an out argument.

But from C# 7.0, excepting a separate variable declaration, the user can also declare the

out variable in the argument list of the method call.

Page 10: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Declaration of out Parameter:

data_typevariable_name;

Method_Name(out variable_name);

Method_Name(out data_typevariable_name);

Here the value of variable_name must be initialized in the called method before it returns a

value.

Example:

using System;

class GFG {

static public void Main()

{

int i;

Addition(out i); // Pass variable i to the method using out keyword

Console.WriteLine("The addition of the value is: {0}", i); // Display the value i

}

public static void Addition(out int i) //Method in which out parameter is passed & this method

{ returns the value of the passed parameter

i = 30;

i += i;

}

}

Output:

The addition of the value is: 60

Difference between Ref and Out keywords in C#

The out is a keyword in C# which is used for the passing the arguments to methods as a

reference type. It is generally used when a method returns multiple values. The out parameter

does not pass the property.

Example :

Using System;

Class GFG {

static public void Main()

Page 11: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

{ int G;

Sum(out G);

Console.WriteLine("The sum of"+ " the value is: {0}", G);

}

public static void Sum(out int G)

{

G = 80;

G += G;

} }

Output:

The sum of the value is: 160

The ref is a keyword in C# which is used for the passing the arguments by a reference. Or we

can say that if any changes made in this argument in the method will reflect in that variable when

the control return to the calling method. The ref parameter does not pass the property.

Example:

using System;

class GFG {

public static void Main()

{ stringstr = "Geek"; // Pass as a reference parameter

SetValue(refstr);

Console.WriteLine(str);

}

static void SetValue(refstringstr1)

{ if(str1 == "Geek") // Check parameter value

{ Console.WriteLine("Hello!!Geek"); }

Page 12: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

str1 = "GeeksforGeeks";

} }

Output:

Hello!!Geek

GeeksforGeeks

Difference between Ref and Out keywords

ref keyword out keyword

It is necessary the parameters should initialize

before it pass to ref.

It is not necessary to initialize parameters

before it pass to out.

It is not necessary to initialize the value of a

parameter before returning to the calling method.

It is necessary to initialize the value of a

parameter before returning to the calling

method.

The passing of value through ref parameter is useful

when the called method also need to change the

value of passed parameter.

The declaring of parameter through out

parameter is useful when a method return

multiple values.

When ref keyword is used the data may pass in bi-

directional.

When out keyword is used the data only

passed in unidirectional.

Note: Both ref and out parameter treated same at compile-time but different at run-time.

METHOD OVERLOADING:

Method Overloading is the common way of implementing polymorphism. It is the ability to

redefine a function in more than one form. A user can implement function overloading by

defining two or more functions in a class sharing the same name. C# can distinguish the methods

with different method signatures. i.e. the methods can have the same name but with different

parameters list (i.e. the number of the parameters, order of the parameters, and data types of the

parameters) within the same class.

• Overloaded methods are differentiated based on the number and type of the parameters

passed as arguments to the methods.

Page 13: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

• You cannot define more than one method with the same name, Order and the type of the

arguments. It would be compiler error.

• The compiler does not consider the return type while differentiating the overloaded

method. But you cannot declare two methods with the same signature and different return

type. It will throw a compile-time error. If both methods have the same parameter types,

but different return type, then it is not possible.

Why do we need Method Overloading?

If we need to do the same kind of the operation in different ways i.e. for different inputs. In the

example described below, we are doing the addition operation for different inputs. It is hard to

find many different meaningful names for single action.

Different ways of doing overloading methods-

Method overloading can be done by changing:

1. The number of parameters in two methods.

2. The data types of the parameters of methods.

3. The Order of the parameters of methods.

By changing the Number of Parameters

class GFG

{

public int Add(int a, int b)

{

int sum = a + b;

return sum;

}

public int Add(int a, int b, int c)

{

int sum = a + b + c;

return sum;

}

public static void Main(String[] args)

{

GFG ob = new GFG();

int sum1 = ob.Add(1, 2);

Console.WriteLine("sum of the two "+ "integer value : " + sum1);

int sum2 = ob.Add(1, 2, 3);

Console.WriteLine("sum of the three "+ "integer value : " + sum2);

}

}

Page 14: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Output:

sum of the two integer value : 3

sum of the three integer value : 6

| Method returning an object

In C#, a method can return any type of data including objects. In other words, methods are

allowed to return objects without any compile time error.

using System;

class Triangle

{

int Base;

int Height;

public Triangle(int b, int h)

{

Base = b;

Height = h;

}

public int Area() // Method return area of triangle

{

return ((Base * Height) / 2);

}

public void Display()

{

Console.WriteLine("Base of the triangle is: "+ Base + "Height of the triangle is:" + Height);

}

public Triangle newdimension(int d)

{

return new Triangle(Base * d, Height * d); } }

class GFG

{

public static void Main()

{ Triangle t1 = new Triangle(2, 8);

Console.Write("Dimensions of Triangle is: ");

t1.Display();

Console.Write("Area of Triangle is: {0}", t1.Area());

Console.WriteLine();

Console.WriteLine();

Triangle t2 = t1.newdimension(2);

Console.Write("New Dimensions of Triangle is: ");

t2.Display();

Console.Write("New area of Triangle is: {0}", t2.Area());

}

}

Page 15: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Output:

Dimensions of Triangle is:

Base of the triangle is: 2

Height of the triangle is: 8

Area of Triangle is: 8

New Dimensions of Triangle is:

Base of the triangle is: 4

Height of the triangle is: 16

New area of Triangle is: 32

CONSTRUCTOR OVERLOADING

It is quite similar to the Method Overloading. It is the ability to redefine a Constructor in

more than one form. A user can implement constructor overloading by defining two or more

constructors in a class sharing the same name. C# can distinguish the constructors with different

signatures. i.e. the constructor must have the same name but with different parameters list.

Can overload constructors in different ways as follows:

• By using different type of arguments

• By using different number of arguments

• By using different order of arguments

By changing the Data types of the parameters

Example:

public ADD (int a, float b);

public ADD (string a, int b);

Here the name of the class is ADD. In first constructor there are two parameters, first one

is int and another one is float and in second constructor, also there is two parameters, first one is

string type and another one is int type.

Here the constructors have the same name but the types of the parameters are different, similar to

the concept of method overloading.

using System;

class ADD

{

int x, y;

double f;

string s;

public ADD(int a, double b) // 1st constructor

{

x = a;

Page 16: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

f = b;

}

public ADD(int a, string b) // 2nd constructor

{

y = a;

s = b;

}

public void show() // showing 1st constructor's result

{

Console.WriteLine("1st constructor (int + float): {0} ",(x + f));

}

public void show1() // shows 2nd constructor's result

{

Console.WriteLine("2nd constructor (int + string): {0}",(s + y));

} }

class GFG // Driver Class

{

static void Main()

{

ADD g = new ADD(10, 20.2);

g.show();

ADD q = new ADD(10, "Roll No. is ");

q.show1();

}

}

MAIN METHOD IN C#

C# applications have an entry point called Main Method. It is the first method which gets

invoked whenever an application started and it is present in every C# executable file. The

application may be Console Application or Windows Application. The most common entry point

of a C# program is static void Main() or static void Main(String []args).

Different Declaration of Main() Method

Below are the valid declarations of Main Method in a C# program:

1. With command line arguments: This can accept n number of array type parameters

during the runtime.

Page 17: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Example:

usingSystem;

classGFG

{ static public void Main(String[] args)

{ Console.WriteLine("Main Method"); } }

Output:

Main Method

Meaning of the Main Syntax:

✓ static: It means Main Method can be called without an object.

✓ public: It is access modifiers which means the compiler can execute this from

anywhere.

✓ void: The Main method doesn’t return anything.

✓ Main(): It is the configured name of the Main method.

String []args: For accepting the zero-indexed command line arguments. args is the

user-defined name. So you can change it by a valid identifer. [] must come before the

args otherwise compiler will give errors.

2. Without Command line arguments: It is up to the user whether he wants to take

command line arguments or not. If there is a need for command-line arguments then the

user must specify the command line arguments in the Main method.

Example:

usingSystem;

classGFG {

static public void Main()

{ Console.WriteLine("Main Method"); } }

Output:

Main Method

Applicable Access Modifiers: public, private, protected, internal, protected internal

access modifiers can be used with the Main() method. The private protected access

Page 18: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

modifier cannot be used with it.

usingSystem;

classGFG

{ protected static void Main()

{ Console.WriteLine("Main Method"); } }

Output:

Main Method

Example:

Using System;

Class GFG

{ private protected static void Main()

{ Console.WriteLine("Main Method"); } }

Output:

Compiler Error:

More than one protection modifier specified

1. Without any access modifier: The default access modifier is private for a Main()

method.

Example:

Using System;

class GFG

{ Static void Main() // Main Method without any access modifier

{ Console.WriteLine("Main Method"); } }

Page 19: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Output:

Main Method

1.Order of Modifiers: The user can also swap positions of static and applicable modifiers

in Main() method.

Example:

Output:

Main Method

1.Return Type: The Main Method can also have integer return type. Returning an integer value

from Main() method cause the program to obtain a status information. The value which is

returned from Main() method is treated as the exit code for the process.

Example:

using System;

class GFG

{ static int Main() // Main Method with int return type

{ Console.WriteLine("Main Method"); // for successful execution of code

return 0; } }

Output:

Main Method

Important Points:

•The Main() method is the entry point a C# program from where the execution starts.

•Main() method must be static because it is a class level method. To invoked without any

instance of the class it must be static. Non-static Main() method will give a compile-time error.

Using System;

Class GFG

{ public static void Main()

{ Console.WriteLine("Main Method"); }}

Page 20: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

•Main() Method cannot be overridden because it is the static method. Also, the static method

cannot be virtual or abstract.

•Overloading of Main() method is allowed. But in that case, only one Main() method is

considered as one entry point to start the execution of the program.

Example: Valid Overloading of Main() Method

// C# program to demonstrate the Valid overloading of Main() method

using System;

class GFG

{ static void Main() // Main method it can also be written as static void Main(String []args)

{ Console.WriteLine("Main Method"); }

static void Main(int n) // overloaded Main() Method

{ Console.WriteLine("Overloaded Main Method"); }

static void Main(int x, int y) // overloaded Main() Method

{ Console.WriteLine("Overloaded Main Method"); }}

Output: Main Method

STATIC CLASS

In C#, one is allowed to create a static class, by using static keyword. A static class can

only contain static data members, static methods, and a static constructor. It is not allowed to

create objects of the static class. Static classes are sealed, means you cannot inherit a static class

from another class.

Syntax:

static class Class_Name

{

// static data members

// static method

}

In C#, the static class contains two types of static members as follows:

Page 21: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

• Static Data Members: As static class always contains static data members, so static data

members are declared using static keyword and they are directly accessed by using the

class name. The memory of static data members is allocating individually without any

relation with the object.

Synatx:

static class Class_name

{

public static nameofdatamember;

}

• Static Methods: As static class always contains static methods, so static methods are

declared using static keyword. These methods only access static data members, they can

not access non-static data members.

Synatx:

static class Class_name

{ public static nameofmethod()

{ // code

} }

// C# program to illustrate the concept of static class

using System;

namespace ExampleOfStaticClass

{ static class Author // Creating static class // Using static keyword

{ public static string A_name = "Ankita"; // Static data members of Author

public static string L_name = "CSharp";

public static intT_no = 84;

public static void details() // Static method of Author

{ Console.WriteLine("The details of Author is:"); }

}

Page 22: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

// Driver Class

public class GFG

{ static public void Main() // Main Method

{ Author.details(); // Calling static method of Author

Console.WriteLine("Author name :{0} ", Author.A_name); // Accessing the static data

Console.WriteLine("Language : {0} ", Author.L_name); members of Author

Console.WriteLine("Total number of articles : {0} ", Author.T_no);

} } }

Output:

The detail of Author is:

Author name: Ankita

Language: CSharp

Total number of articles: 84

Difference between static and non-static class

Static Class Non-Static Class

Static class is defined using static keyword. Non-Static class is not defined by using static

keyword.

In static class, you are not allowed to create

objects.

In non-static class, you are allowed to create

objects using new keyword.

The data members of static class can be

directly accessed by its class name.

The data members of non-static class is not

directly accessed by its class name.

Static class always contains static members. Non-static class may contain both static and non-

static methods.

Static class does not contain an instance

constructor. Non-static class contains an instance constructor.

Static class cannot inherit from another class. Non-static class can be inherited from another

class.

Page 23: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

OPERATOR OVERLOADING

C# | Operator Overloading

o The concept of overloading a function can also be applied to operators. Operator

overloading gives the ability to use the same operator to do various operations.

o It enables to make user-defined implementations of various operations where one or both

of the operands are of a user-defined class.

o To make operations on a user-defined data type is not as simple as the operations on a

built-in data type.

o To use operators with user-defined data types, they need to be overloaded according to a

programmer’s requirement.

o An operator can be overloaded by defining a function to it. The function of the operator is

declared by using the operator keyword.

Syntax:

access specifierclassName operator Operator_symbol (parameters)

{

// Code

}

The following table describes the overloading ability of the various operators available in

C#:

Operators Description

+, -, !, ~, ++, – – unary operators take one operand and can be overloaded.

+, -, *, /, % Binary operators take two operands and can be overloaded.

==, !=, = Comparison operators can be overloaded.

&&, || Conditional logical operators cannot be overloaded directly

+=, -+, *=, /=, %=, = Assignment operators cannot be overloaded.

Page 24: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Overloading Unary Operators

The return type can be of any type except void for unary operators like! ~, + and dot (.) but the

return type must be the type of ‘Type’ for – and ++ operators and must be a bool type for true as

well as false operators. But do remember that the true and false operators can be overloaded as

pairs only. The compilation error arises if a class declares one of these operators without

declaring the other.

using System;

namespace Calculator

{ class Calculator

{ public int number1 , number2;

public Calculator(int num1 , int num2)

{ number1 = num1;

number2 = num2; }

public static Calculator operator-(Calculator c1) // Function to perform operation

{ c1.number1 = -c1.number1; // By changing sign of integers

c1.number2 = -c1.number2;

return c1; }

public void Print() // Function to print the numbers

{ Console.WriteLine ("Number1 = "+ number1);

Console.WriteLine ("Number2 = "+ number2);

} }

Class EntryPoint

{ staticvoidMain(String []args) // Driver Code

{ Calculator calc = newCalculator(15, -25);

calc = -calc;

calc.Print();

} }}

Page 25: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Output :

Number1 = -15

Number2 = 25

Overloading Binary Operators

Binary Operators will work with two Operands. Examples of binary operators include the

Arithmetic Operators (+, -, *, /, %), Arithmetic Assignment operators (+=, -+, *=, /+, %=)

and Relational Operators etc. Overloading a binary operator is similar to overloading a

unary operator, except that a binary operator requires an additional parameter.

Syntax:

Operator operator (object1, object2);

Here, second "operator" is a symbol that denotes a binary operator.

operator + (a, b);

Example :

Input : 200, 40

Output : 240

// C# program to illustrate the Binary Operator Overloading

using System;

namespace BinaryOverload

{ class Calculator

{ public int number = 0;

public Calculator() {} // no-argument constructor

public Calculator(int n) // parameterized constructor

{ number = n; }

public static Calculator operator+ (Calculator Calc1,Calculator Calc2)

{

Calculator Calc3 = new Calculator(0);

Calc3.number = Calc2.number + Calc1.number;

return Calc3;

}

Page 26: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

Indexers

public void display() // function to display result

{ Console.WriteLine("{0}", number); }

}

Class CalNum

{ static void Main(string[] args) // Driver Code

{ Calculator num1 = new Calculator(200);

Calculator num2 = new Calculator(40);

Calculator num3 = new Calculator();

num3 = num1 + num2;

num1.display(); // Displays 200

num2.display(); // Displays 40

num3.display(); // Displays 240

}

}

}

Output :

200

40

240

Benefits of Operator Overloading:

▪ Operator overloading provides additional capabilities to C#

operators when they are applied to user-defined data types.

▪ Operators may be considered as functions internal to the

compiler.

Page 27: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

✓ An indexer allows an instance of a class or struct to be indexed as an array.

✓ If the user will define an indexer for a class, then the class will behave like a virtual array.

✓ Array access operator i.e. ([ ]) is used to access the instance of the class which uses an

indexer.

✓ A user can retrieve or set the indexed value without pointing an instance or a type

member. Indexers are almost similar to the Properties. The main difference between

Indexers and Properties is that the assessors of the Indexers will take parameters.

Syntax:

[access_modifier] [return_type] this [argument_list]

{

get

{

// get block code

}

set

{

// set block code } }

In the above syntax:

• access_modifier: It can be public, private, protected or internal.

• return_type: It can be any valid C# type.

• this: It is the keyword which points to the object of the current class.

• argument_list: This specifies the parameter list of the indexer.

• get{ } and set { }: These are the accessors.

Example:

// C# program to illustrate the Indexer

using System;

class IndexerCreation

{ private string[] val = new string[3]; // Indexer declaration

public string this[int index] // Indexer and "this" is the keyword

{ get

{ return val[index]; }

set

{ val[index] = value; } }

Page 28: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

}

class main // Driver Class

{ public static void Main() // Main Method

{ IndexerCreation ic = new IndexerCreation();

ic[0] = "C";

ic[1] = "CPP";

ic[2] = "CSHARP";

Console.Write("Printing values stored in objects used as arrays\n");

Console.WriteLine("First value = {0}", ic[0]);

Console.WriteLine("Second value = {0}", ic[1]);

Console.WriteLine("Third value = {0}", ic[2]);

} }

Output:

Printing values stored in objects used as arrays

First value = C

Second value = CPP

Third value = CSHARP

Important Points about Indexers:

• There are two types of Indexers i.e. One Dimensional Indexer&MultiDimensional

Indexer. The above discussed is One Dimensional Indexer.

• Indexers can be overloaded.

• These are different from Properties.

• This enables the object to be indexed in a similar way to arrays.

• A set accessor will always assign the value while the get accessor will return the value.

• “this” keyword is always used to declare an indexer.

• To define the value being assigned by the set indexer, “value” keyword is used.

• Indexers are also known as the Smart Arrays or Parameterized Property in C#.

• Indexer can’t be a static member as it is an instance member of the class.

PROPERTIES

Page 29: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

The two reasons for using properties in C#:

• If the members of a class are private then how another class in C# will be able to read,

write, or compute the value that field.

• If the members of the class are public then another class may misuse that member.

Using Properties

➢ Properties are the special type of class members that provides a flexible mechanism to

read, write, or compute the value of a private field.

➢ Properties can be used as if they are public data members, but they are actually special

methods called assessors.

➢ This enables data to be accessed easily and help to promote the flexibility and safety of

methods. Encapsulation and hiding of information can also be achieved using properties.

➢ It uses pre-define methods which are “get” and “set” methods which helps to access and

modify the properties.

Accessors: The block of “set” and “get” is known as “Accessors”. It is very essential to restrict

the accessibility of property. There are two type of accessors i.e. get assessors and set accessors.

There are different types of properties based on the “get” and set assessors:

•Read and Write Properties: When property contains both get and set methods.

•Read-Only Properties: When property contains only get method.

•Write Only Properties: When property contains only set method.

•Auto Implemented Properties: When there is no additional logic in the property accessors and it

introduce in C# 3.0.

The syntax for Defining Properties:

<access_modifier><return_type><property_name>

{ get { // body }

set { // body }

}

Where, <access_modifier> can be public, private, protected or internal. <return_type> can be

any valid C# type. <property_name> can be user-defined. Properties can be different access

modifiers like as public, private, protected, internal.

Access modifiers define how users of the class can access the property. The get and set accessors

for the same property may have different access modifiers.

Page 30: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

A property may be declared as a static property by using the static keyword or may be marked as

a virtual property by using the virtual keyword.

•Get Accessor: It specifies that the value of a field can access publicly. It returns a single value

and it specifies the read-only property.

Example:

class Geeks {

private int roll_no; // Declare roll_no field

public int roll_no // Declare roll_no property

{ get

{ return roll_no; } }

}

•Set Accessor: It will specify the assignment of a value to a private field in a property. It returns

a single value and it specifies the write-only property.

Example:

class Geeks {

private int roll_no; // Declare roll_no field

public int roll_no // Declare roll_no property

{ get

{ return roll_no; }

set

{ roll_no = value; }

}

}

Accessor Accessibility

•It can’t use accessor modifiers on an interface or an explicit interface member implementation.

Page 31: CLASSES - WordPress.com · Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call the method Defining Methods in C#

•It can use accessor modifiers only if the property has both set and get accessors.

•If the property is an override modifier, the accessor modifier must match the accessor of the

overridden accessor.

•The accessibility level on the accessor must be more restrictive than the accessibility level on

the property.