0% found this document useful (0 votes)
3 views18 pages

Staticconstructor Namespacenotes 1

The document covers various C# programming concepts including static constructors, dynamic binding, operator overloading, inheritance, abstract classes, the base keyword, boxing and unboxing, structs, enums, interfaces, and generics. Each concept is explained with examples and code snippets to illustrate their usage and functionality. The document serves as a comprehensive guide for understanding these fundamental C# features.

Uploaded by

jlurker77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

Staticconstructor Namespacenotes 1

The document covers various C# programming concepts including static constructors, dynamic binding, operator overloading, inheritance, abstract classes, the base keyword, boxing and unboxing, structs, enums, interfaces, and generics. Each concept is explained with examples and code snippets to illustrate their usage and functionality. The document serves as a comprehensive guide for understanding these fundamental C# features.

Uploaded by

jlurker77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Static constructor:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be
performed only once. It is called automatically called before the first instance is created or any static members are
referenced.

class SimpleClass

// Static variable that must be initialized at run time.

static readonly int value;

// Static constructor is called at most one time, before any

// instance constructor is invoked or member is accessed.

static SimpleClass()

value = 1;

}
C# Dynamic Binding
C# dynamic is a keyword that is used to make a property or a method dynamic. When we make dynamic
type, compiler does not check it at compile-time. Compiler checks it only at run time.

The purpose of using dynamic binding is to avoid compile time checking of the code.

The property created using dynamic keyword works like object. Dynamic variables are compiled
into type object variables and exist only at compile time, not at run time.

The type of dynamic and object both are similar. We can check it by using the following code. using

System;

namespace CSharpFeatures

public class DynamicExample {

public static void Main(string[] args) {


dynamic v = 1;

object v1 = 1;

Console.WriteLine(v.GetType());

Console.WriteLine(v1.GetType()); }

Output:

System.Int32
System.Int32

Another example:

using System;

namespace CSharpFeatures

public class Student

// Creating dynamic property


public dynamic Name { get; set; }

// Creating a dynamic method

public dynamic ShowMSG(string msg)

return msg;

public class DynamicExample

{
public static void Main(string[] args)

Student student = new Student();

student.Name = "Peter";

Console.WriteLine(student.Name);

// Storing result in dynamic object

dynamic msg = student.ShowMSG("Welcome to the javatpoint");

Console.WriteLine(msg);

Output:
Peter
Welcome to the javatpoint
Operator overloading:

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. It provides additional capabilities to C# operators when they are applied to
user-defined data types. It enables to make user-defined implementations of various operations where one or both of
the operands are of a user-defined class. Only the predefined set of 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. It
provides additional capabilities to c# operators when they are applied to user-defined data types. It enables to make
user-defined implementations of various operations where one or both of the operands are of a user-defined class.
Only the predefined set of c# operators can be overloaded. To make operations on a user-defined data type is not as
simple as the operations on a built-in data type. To use operators with user-defined data types, they need to be
overloaded according to a programmer’s requirement. An operator can be overloaded by defining a function to it. The
function of the operator is declared by using the operator keyword,operators can be overloaded. To make operations
on a user-defined data type is not as simple as the operations on a built-in data type. To use operators with user-defined
data types, they need to be overloaded according to a programmer’s requirement. 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 specifier className operator Operator_symbol (parameters) {
// Code
}
// C# program to illustrate the // unary operator

overloading using System;

namespace Calculator {

class Calculator {

public int number1 , number2;

public Calculator(int num1 , int num2) {

number1 = num1;

number2 = num2;

// Function to perform operation // By changing sign of

integers

public static Calculator operator -(Calculator c1) {

c1.number1 = -c1.number1;

c1.number2 = -c1.number2;

return c1;

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

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

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

class EntryPoint

// Driver Code

static void Main(String []args)

// using overloaded - operator

// with the class object

Calculator calc = new Calculator(15, -25);

calc = -calc;

// To display the result

calc.Print();

Inheritance is a process where child object acquires the properties and behaviour of
parent object. Private members cannot be inherited while protected and public members can
be inherited.
Advantages :
reusability:the methods and variables in parent class can be used in all the child
objects without rewriting again,
extendability:child classes can be added as much as required.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOP
{
class Employee
{
public int salary=1000;

}
class Programmer:Employee
{

public int bonus=500;

public int getSalary()


{
return bonus +salary;
}
}
class inheritdemo
{
public static void inheritdemometh()
{

Programmer p = new Programmer();


Console.WriteLine(p.getSalary());

}
}
}
Output:

1500
using System;

Abstract class:
A class that is defined with abstract keyword is known as abstract class. the objects
cannot be created from abstract class.
Other classes can inherit from this class
It can contain methods which does not have body which is called abstract method. Abstract classes
can have both abstract and non abstract methods.

namespace OOP
{
public abstract class ShapeA
{
public abstract float getArea();
public void draw()
{
Console.WriteLine("Drawing shape");
}
}
class Circle : ShapeA
{
public float radius;
public Circle(float rad)
{
this.radius = rad;
}
public override float getArea()
{
return 3.1416f*radius * radius;
}
}
class Rectangle:ShapeA
{
public int length, breadth;
public Rectangle(int len,int bre)
{
length = len;
breadth = bre;
}
public override float getArea()
{
return length*breadth;
}
}
class abstractclassdemo
{
public static void abstractdemometh()
{
ShapeA s;
s = new Circle(3.1f);
Console.WriteLine("The area of circle is:"+s.getArea()); }
}
}

Output:

The area of circle is:30.19077

Base keyword:

The base keyword is used to access members of the base class from within a derived class:

∙ Call a method on the base class that has been overridden by another method. ∙ Specify which
base-class constructor should be called when creating instances of the derived class.

A base class access is permitted only in a constructor, an instance method, or an instance property
accessor.

Example:
namespace OOP
{
class Employee
{
public int salary;

public Employee(int sal)//user defined parametrized {


salary = sal;
}
public Employee()//user definedparameterless
{
salary = 0;
}
}
class Programmer:Employee
{
public new int salary=5000;
public int bonus;
public Programmer(int bon):base()
{
bonus = bon;
}
public Programmer(int sal,int bon):base(sal)//using base keyword to access base
//class constructor.
{
bonus = bon;
}

public int getSalary()


{
return bonus + base.salary;//using base keyword to access base class member. }
}
class inheritdemo
{
public static void inheritdemometh()
{

Programmer p = new Programmer(10000,500);


Programmer p1 = new Programmer(4000);
Console.WriteLine(p1.getSalary());
Console.WriteLine(p.getSalary());

}
}
}

Object Type, Boxing, and Unboxing

Object is the ultimate base class of all the classes in .NET Framework. Object type is the root data type
that can contain a value of any data type, value type, reference type, user type or predefined. We have to
typecast the value before assigning to object type.

When we change a value type variable to object type, it is said to be boxing. On the other hand, when we
change an object type variable to value type, it is said to be unboxing. using System;
namespace OOP
{

public class TutShare


{
public int value1 = 10;
public string value2 = "qwertyuiop"; public void Share()
{
Console.WriteLine("Inside Share method"); }
public void UnBoxingExample()
{
// This is Boxing as we are converting a 'value type' value into 'object type'
object o = "yeepy";

// This is Unboxing as we are converting a 'object type' value into


'value type'
string text = (string)o;
}
static void Main(string[] args)
{
Console.WriteLine("hello Tutpoint");

// Create Object of class TutShare


TutShare tutShare = new TutShare();

// This is boxing as we are assiging a 'value type' value to 'object type' object
obje = 1000;
Console.WriteLine(obje);
//This is another example of boxing obje = tutShare.value1;
Console.WriteLine(obje);
Console.WriteLine(obje.GetType()); // GetType() is used to get the data type

// we are assigning value of 'value2' variable to 'obje' obje = tutShare.value2;


Console.WriteLine(obje);
Console.WriteLine(obje.GetType()); // GetType() is used to get the data type

object objTutShare = new TutShare(); // type casting 'objTutShare' to


'TutShare' type tutShare = (TutShare)objTutShare;
tutShare.Share();

tutShare.UnBoxingExample();

Console.ReadLine();
}

}
Output:

hello Tutpoint

1000
10

System.Int32

qwertyuiop

System.String

Inside Share method

Struct:

In C#, struct is the value type data type that represents data structures. It can contain a parameterized
constructor, static constructor, constants, fields, methods, properties, indexers, operators, events, and
nested types.

struct can be used to hold small data values that do not require inheritance

A structure is declared using struct keyword. The default modifier is internal for the struct and its members.
Example:
using System;

public class Program


{
public static void Main()
{
Coordinate point = new Coordinate();

Console.WriteLine(point.x);
Console.WriteLine(point.y);
}
}

struct Coordinate
{
public int x;
public int y;
}

Output:

0
0

Another Example:
using System;

public class Program

public static void Main()

Employee emp;

//Console.Write(emp.EmpId); // Compile time error

emp.EmpId = 1;

Console.Write(emp.EmpId); // prints 1

struct Employee

public int EmpId;

public string FirstName;

public string LastName;

Structure can have constructor defined within it. Example:

using System;
public class Program

public static void Main()

Coordinate point = new Coordinate(10, 20);


Console.WriteLine(point.x); //output: 10

Console.WriteLine(point.y); //output: 20

struct Coordinate

public int x;

public int y;

public Coordinate(int x, int y)

this.x = x;

this.y = y;

Structs can also have methods and properties as in classes. Example:

using System;

public class Program {

public static void Main()

Coordinate point = new Coordinate();

point.SetOrigin();

Console.WriteLine(point.x); //output: 0
Console.WriteLine(point.y); //output: 0
}

struct Coordinate

public int x { get; set; }

public int y { get; set; }

public void SetOrigin()

this.x = 0;

this.y = 0;

Enums
An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).

To create an enum, use the enum keyword (instead of class or interface), and separate the enum items with
a comma:

Enum values:

By default, the first item of an enum has the value 0. The second has the value 1, and so on. To get the

integer value from an item, you must explicitly convert the item to an int:

Example:
using System;
namespace OOP
{
enum Season
{
SPRING, SUMMER, AUTUMN, WINTER
}
class enumdemo
{
public static void enumdemomethod()
{
Console.WriteLine(Season.SPRING);
Season s1 = Season.AUTUMN;
Console.WriteLine(s1);
int value = (int)Season.WINTER;
Console.WriteLine(value);

}
}
}

Output:

SPRING

AUTUMN

C# Interface
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared
inside the interface are abstract methods. It cannot have method body and cannot be instantiated.

It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve fully
abstraction because it cannot have method body.

Its implementation must be provided by class or struct. The class or struct which implements the interface,
must provide the implementation of all the methods declared inside the interface

Example:

public interface Drawable


{
void draw();
}
public class Rectangle : Drawable
{
public void draw()
{
Console.WriteLine("drawing rectangle..."); }
}
public class Circle : Drawable
{
public void draw()
{
Console.WriteLine("drawing circle..."); }
}
public class TestInterface
{
public static void Main()
{
Drawable d;
d = new Rectangle();
d.draw();
d = new Circle();
d.draw();
}

Output:

drawing rectangle...
drawing circle...

Example of multiple inheritance using interface: using System;

using System;
namespace OOP
{
interface AA
{
void run();

}
interface BB
{
void run();
}
public class interfacedemo : AA, BB//multiple inheritance {
public void run()
{
Console.WriteLine("I am running ...");
}
}
public class MIDemo
{
public static void Main()
{
interfacedemo idemo = new interfacedemo();
idemo.run();
}

}
}

After executing MIDemo.Main() the output will be:

I am running…
Generics allow you to define the specification of the data type of programming elements in a class or a
method, until it is actually used in the program. In other words, generics allow you to write a class or
method that can work with any data type.

You write the specifications for the class or the method, with substitute parameters for data types. When the
compiler encounters a constructor for the class or a function call for the method, it generates code to handle
the specific data type. A simple example would help understanding the concept

using System;
using System.Collections.Generic;

namespace GenericApplication {
public class MyGenericArray<T> {
private T[] array;

public MyGenericArray(int size) {


array = new T[size + 1];
}
public T getItem(int index) {
return array[index];
}
public void setItem(int index, T value) { array[index] = value;
}
}
class Tester {
static void Main(string[] args) {

//declaring an int array


MyGenericArray<int> intArray = new MyGenericArray<int>(5);
//setting values
for (int c = 0; c < 5; c++) {
intArray.setItem(c, c*5);
}

//retrieving the values


for (int c = 0; c < 5; c++) {
Console.Write(intArray.getItem(c) + " "); }

Console.WriteLine();

//declaring a character array


MyGenericArray<char> charArray = new MyGenericArray<char>(5);
//setting values
for (int c = 0; c < 5; c++) {
charArray.setItem(c, (char)(c+97));
}

//retrieving the values


for (int c = 0; c< 5; c++) {
Console.Write(charArray.getItem(c) + " "); }
Console.WriteLine();

Console.ReadKey();
}
}
}

Output:
0 5 10 15 20
a b c d e

Generic Methods:

In the previous example, we have used a generic class; we can declare a generic method with a type
parameter. The following program illustrates the concept –

using System;
using System.Collections.Generic;

namespace GenericMethodAppl {
class Program {
static void Swap<T>(ref T lhs, ref T rhs) { T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args) {
int a, b;
char c, d;
a = 10;
b = 20;
c = 'I';
d = 'V';

//display values before swap:


Console.WriteLine("Int values before calling swap:"); Console.WriteLine("a = {0},
b = {1}", a, b); Console.WriteLine("Char values before calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
//call swap
Swap<int>(ref a, ref b);
Swap<char>(ref c, ref d);

//display values after swap:


Console.WriteLine("Int values after calling swap:"); Console.WriteLine("a = {0},
b = {1}", a, b); Console.WriteLine("Char values after calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
Console.ReadKey();
}
}
}

Output:

Int values before calling swap:


a = 10, b = 20
Char values before calling swap:
c = I, d = V
Int values after calling swap:
a = 20, b = 10
Char values after calling swap:
c = V, d = I

You might also like