C# > Types in c#

Types in c# in C#

How To declare different types in c#


Classes:

Class is a reference type which enables to create own custom types by grouping the variables of other types, events and functions.

The declaration of the class

class Myclass
{
    .... class body
}

In the above code we have declared class as Myclass which defines as base class and class body defines the Fields, Events, constructors, Methods. Class defines the data of the type.

     

Objects:

object is an instance of the class. Class defines the object but it can not be an object. A program may create many objects of the same class  they can be stored in either a named variable or in an array or collection.

The declaration of the object to a class :

MyClass obj1 = new MyClass();

In the above code we have created the instance(object) to the class Myclass. obj1 is a reference to the myclass which refers new object with out any data.    

Class inheritance:

Inheritance is defined as deriving from base class to the derived class. Base class means parent and derived class is called child.

Example program on inheritance 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace example
{
    class Program
    {

        class a
        {
            public void display()
            {
                System.Console.WriteLine("www.dotnetfunda.com");
            }
        }
        class b : a 
        {
            public void display1()
            {
                System.Console.WriteLine("www.techfunda.com");
            }
        }

        class c
        {
            public static void Main()
            {
                b x = new b();
                x.display();
                x.display1();
            }
        }
    }
}

In the above code snippet we have defined class inheritance. We have taken three classes in this program  as class a, class b and class c. Class a as (base class) and class b as (derived class) and class c as function to declare the base class and derived class. We have taken class as program and in the class a We have given public void display(), The console.writeline("www.techfunda.com") prints the value as www.techfunda.com. In the class b the derived class of class a (baseclass) We have public void display1() as the system.consol.writeline ("www.dotnetfunda.com") prints the value as www.dotnetfunda.com and in the class c we have declaring  the b x=new b(); and x.display() and x.display1() prints the value as www.techfunda .comand www.dotnetfunda.com.

output

Fields:

Filed is the variable which is the member of the class which are directly declared in the class or structs, A class can use instance fields dnd static fields or both.

The declaration of the field

public class Myclass
{
    public int a; //Field
}

In the above code we have given class as myclass and the fields are written in the brackets.

There are different types of fields modified by field modifiers they are

  • Access modifiers
    • public 
    • internal
    • private 
    • protected
  • static modifier
  • Inheritance modifier
  • unsafe code modifier
  • Read only modifier
  • Threading modifier         


Access modifiers 

Access modifiers are the keywords which are used to access the memeber or a type. There are four types of access modifier they are

public access modifier

public access modifiers are having no restrictions to access public members. These are called from external location. These can be accessed by member or class. 

The declaration of public access modifier is 

public class MyClass
{
    .........;        // It can be accessed by any one
}

In the above code we have declared class as Myclass and the type can be accessed by any class, field and methods.


private access modifier:

private access modifier is defined as it access the member of the same class, It  linits the access in its own class.


The declaration of private access modifier is

private class MyClass
{
    .........;       // It can be accessed with in the class and within the assembly.
}

In the above code snippet we have declared the private access modifier. In this we have defined class as Myclass . The private access modifier is accessed is modified in its class only.


Protected access modifier

It is accessed in its class and with in the derived class instances. It is same as public but allows the derived class to access the member.

The declaration of protected access modifier

protected class MyClass
{
    .........;        // It can be accessed within this class and classes derived from it.
}

In the above code we have declared the protected access modifier. We have taken class as Myclass and the protected access modifier it access with in its class and the class derived from it.


Internal access modifier:

It provides access limited to the classes of current project assembly. A type can be accessed by any members in the same assembly and limits the accessibility for another assembly types. 

The declaration of internal access modifier

internal class MyClass
{
    ..........;      // It can be accessed by classes of current assembly.
}

In the above code snippet we have defined the internal access modifier it access the current assemly by its classes.


Protected internal modifier:

It protects the class of both protected and internal class by its current assembly as well as derived class type.

The declaration of protected internal access modifier:

protected internal MyClass
{
    .........;       // It can be accessed by current project classes and derived classes.
}

 

Static Modifier:

Static is a keyword which declares the static member to the type itsself rather than the specific object, It uses methods , classes, constructors etc. It takes one location in the memory and it will shared from there. It improves the performance of the program and it provides less flexibility. 

The declaration of static modifier: 

static class MyClass
{
    static int a;               // static variable
    public static void fruits() // static method
    {
        .......;
    }
}

In the above code snippet we have defined how to declare the static modifier. In this example it defines the variables and methods usig static modifier.      

Example program on static keyword

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
static class Techfunda
{
    public static int _value = 9;
}

class Program
{
    static void Main()
    {
        Console.WriteLine(++Techfunda._value);
    }
}

In the above code snippet we have defined the static keyword. We have taken class as TechFunda and in the main function of class techfunda we have given the int value as 9 and in the main function of class program we have console.writeline as (++techfunda._value). which prints the value with increment by one.

output

 


unsafe code modifier:

Pointers which operates requires the unsafe context. This type of keyword is denoted by unsafe keyword of unsafe code modifier.

The declaration of unsafe code modifier

class MyClass
{
    public unsafe void Test() // using unsafe keyword
    {
        int a;                // unsafe context
        int b;                // unsafe context
        // unsafe context.
        // pointers can be used here.
    }
}


Read Only

The readonly is a keyword which is used to prevent the fields from being changed. They can be initiliazed at run time as constant values

The declaration of Readonly

public class MyClass
{
    readonly int fruits = 5; // Read only
}

 In the above example, the field (fruits) has used readonly modifier in which the value of the fruits cannot be changed in the MyClass method.


Volatile

Volatile is the keyword where the modification is done by threads. It is used for the fields by executing the multiple threads.   

The declaration of volatile

class MyClass
{
    public volatile int a; // public field as volatile

    MyClass(int b)
    {
        a = b;
    }
}

Volatile can be used to different types of the following  

  • Pointer types
  • Reference types
  • Integral types
  • Generic types  

       

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 the method we need to

  •              Define the method
  •              Call the method 
The declaration of a method in c#
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
   Method Body
}

Methods allows following modifiers
They are
  • Static modifier-static
  • Access modifier
    • public
    • private
    • internal
    • protected
  • Inheritance modifiers
    • new 
    • abstract
    • virtual
    • override
    • sealed
  • Partial method modifier
    • partial
  • Unmanaged code modifiers
    • unsafe extern

Inheritance modifiers:

Inheritance is a relationship that defines one entity in terms of another. Class inheritance defines a new class in terms of one parent class or one or more interfaces. The new class inherits its interface and implementation from its parent class and method signatures. The new class is called a subclass or a derived class. 

New modifier

The new modifier is a key word which explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version.
 
The declaration of new keyword
public class BaseC
{
    public int x;
    public void Invoke() { }
}
public class DerivedC : BaseC
{
    new public void Invoke() { }
}
In the above code , BaseC.Invoke is hidden by DerivedC.Invoke. The field x is not affected because it is not hidden by a similar name.

Abstract modifier:

An abstract method has no implementation. Its implementation logic is provided instead by classes that derive from it. We use an abstract class to create a base template for derived classes.
The declaration of the abstract
public abstract int Find();
 
Example program on Abstract
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
abstract class Test
{
    public int _a;
    public abstract void A();
}

class Example1 : Test
{
    public override void A()
    {
        Console.WriteLine("techfunda");
        base._a++;
    }
}

class Example2 : Test
{
    public override void A()
    {
        Console.WriteLine("dotnetfunda");
        base._a--;
    }
}

class Program
{
    static void Main()
    {
        
        Test test1 = new Example1();
        test1.A();

        
        Test test2 = new Example2();
        test2.A();
    }
}
In the above code snipet we have defined the abstract  method. We have taken class as Test and we have declared the public int_a; and public abstract void A()   and we have taken two classes as example 1 and example 2 in the class example 1 we declared the test and in the main function of this class we have given the techfunda in console.writeline and in the class example 2 we have given the dotnetfunda in the console.Writeline, In the main function of the class program we have given   Test test1 =new example 1 and test1.A(); and in the Test test2 = new example 2  as test2.A(); which prints the out put as techfunda and dotnetfunda.


output

Virtual

Virtual is a keyword  which is used to modify a type and allows that type to get overridden in the derived classes. In other words, a virtual method can be overridden by any derived classes which means it is a method that can be redefined.

The declaration of virtual keyword

class Base
{
    protected virtual void Test() 
    {
        ..............;
    }
}
class Derived : Base
{
    protected override void Test() 
    {
        ..............;
    }
}

Now, in the above syntax we have two classes Base and Derived (Which inherits Base). We have called the virtual methods of the Base class in the Derived class by using override keyword.


sealed 

sealed is a C# keyword which is used to seal a class and prevent it to get inherited from any other classes. In other words, a sealed class cannot be inherited.

The declaration of sealed class is 

sealed class Box  
{
    ........;         
    .......;
}

In a base class, sealed modifiers can be used on method or function that overrides a virtual method. This will allow us to derive the functions from the base class and preventing that specific virtual method.


Method overloading

Creating multiple methods in a class with a same name but different parameters and types is called method overloading  Method overloading is a compile time polymorphism which is done at compile time.

Example program on Method overloading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Class1
    {

        public int Sum(int A, int B)
        {
            return A + B;
        }

        public float Sum(int A, float B)
        {
            return A + B;
        }
    }

    class Class2 : Class1
    {
        public int Sum(int A, int B, int C)
        {
            return A + B + C;

        }
    }

    class MainClass
    {
        static void Main()
        {

            Class2 obj = new Class2();

            Console.WriteLine(obj.Sum(5, 2));

            Console.WriteLine(obj.Sum(1, 5.70f));

            Console.WriteLine(obj.Sum(1, 0, 3));

            Console.Read();
        }

    }

In the above code snipet we have defined method overloading. We have taken two classes named class1 and class 2 and in the class1 we have defined the public int sum( inta, intb) which returns (a+b) and public float( inta, float b ), Which returns (a+b). In the class2 we have assigned class2 to class1 and in the main function of class2 we are declaring public int sum( inta, intb, intc). which returns the (a+b+c). We are having another class as mainclass, In this main function of mainclass  we are assigning class 2 obj =new class2(), In the nextline we are assigning the console.Writeline as (obj.sum(5,2)); prints the value as 7 and  Console.WriteLine(obj.Sum(1, 5.70f)); prints the value as int value is 1 and float value as 5.70 which adds the value as 6 and o value floats the value to point 7 and  Console.WriteLine(obj.Sum(1, 0, 3)); prints the value as 4 in the output and the console.Read()  reads the values in the output.      

output


 

Method overriding 

Creating method in a derived class with same name, same parameters and same return type as in base class is called as method overriding. Method overriding is an example program of run time polymorphism


Example program of Method overriding 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class BaseClass
    {
        public virtual string YourCity()
        {
            return "Hyderabad";
        }
    }

    class DerivedClass : BaseClass
    {
        public override string YourCity()
        {
            return "Delhi";
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            DerivedClass obj = new DerivedClass();
            string city = obj.YourCity();
            Console.WriteLine(city);
            Console.Read();
        }
    }

In the above code snippet we have defined the method overriding. We have taken taken two classes as class baseclass and class derivedclass. In the baseclass we have declared public virtual string your city and returns hyderabad. In the derived class we have declared derived class to baseclass and declared as public override string your city() and returns as delhi, We have taken class as program, In the main function of class program We have Derivedclass obj = new Derivedclass(); which defines the value of new derived class and string city= obj.yourcity(); prints the value in the derived class and console.writeline ( city ) prints the value as delhi and console.Read() reads the value in the output.

output

Passing parameters to Methods

  • value parameters
  • Reference parameters

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.


Example program value parameters

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class program
{
    public struct point
    {
        public int A, B;
    }
    static void main()
    {
        point p1 = new point();
        p1.A = 21;
        point p2 = p1;
        Console.WriteLine(p1.A);
        Console.WriteLine(p2.A);
        p1.A = 50;
        Console.WriteLine(p1.A);
        Console.WriteLine(p2.A);

    }
}

In the above code snippet we have declared two integers a, b using int data type, In the main method we created an object p1 for struct point, Finally we are calling the variable p1.A with that object. We also created the copy (p2) of objectp1 we can use this object for different work around. Later we are changing the value of p1.A as 50.

output

Reference parameters

Reference type store references to that object, It is more complex than a value type which is having two parts, object and the reference to that object. The content of a reference type variable or constant is reference to an object that contains the value      
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        string msg = "Hello, Welcome to C#";
        string upperMsg = msg.ToUpper();
        Console.WriteLine(upperMsg);

        double a = 5.0;
        msg = msg + " " + a.ToString();
        Console.WriteLine(msg);
    }
}
In the above code snippet We used reference type parameter. In order to make string uppercase we use Toupper() method, Double is a another data type value which is used to define the decimal value    

output


Events

Event is a keyword used to perform an action, which provides notifications to the clients. The keyword delegate is used while declaring the event

The declaration of the events 

public delegate void fruit();

The above code specifies it as a event

public event fruit; 

The above code declares the event

Example program on Events

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public delegate void Handler(); 
 class Program
    {
        public static event Handler menu;  

        static void Main()
        {
            menu += new Handler(Birthdays); 
            menu += new Handler(Meetings);  
            menu += new Handler(Reminders); 

            menu.Invoke();                 
        }

        static void Birthdays()
        {
            Console.WriteLine("Today is Nehru's birthday");
        }

        static void Meetings()
        {
            Console.WriteLine("Today's Meetings.....");
        }

        static void Reminders()
        {
            Console.WriteLine("Remind to do ......");
        }
    }

In the above code snippetwe have declared the Events. We have taken class as program and in the main function this class we have declared the event and in the main function of the program we have menu+=new handler as birthday, menu+=new handler as meeting and menu+=new handler as remind to go and in the main function of birthday we have written as Nehrus bithday, In the main function of meeting we have defined as todays meeting and in the main function of the reminders we have remind to go

output

Constants

Constant is a keyword which may be of data type like integer constant, character constant, Floating constant. 

Example program to declare the constant

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
    {
        const string Name = "Techfunda"; 
        static void Main()
        {
            Console.WriteLine("Name: " + Name);
            

            const int Num = 8;        
           
            Console.WriteLine("No: " + Num);
        }
    }

In the above code snippetwe have declare the constant we have taken class as program and in the main function  we defined constant as string name called techfunda and the console.witeline prints as techfunda and constant int number prints the value as in the output

output

Properties 

properties are the extension of the fields. Classes, structures, interface are definedas properties

Example program on properties

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
    class Student
    {
        
        private string name = "not known";
        private int age = 0;

       
       
        
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        
        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
            }
        }
        public override string ToString()
        {
            return "Name=  " + Name + ", Age = " + Age;
        }
    }

    class program
    {
        public static void Main()
        {

            
            Student s = new Student();

                      
            s.Name = "Techfunda";
            s.Age = 9;
            Console.WriteLine("Student Info: {0}", s);

            
            s.Age += 1;
            Console.WriteLine("Student Info: {0}", s);
            Console.ReadKey();
        }
    }
}

In the above code snippet we have defined properties we have defined private string name and int age in the function In public string name we have get and set  which returns name and value and in the public int age we have get and set which returns age and value, In Public override string To Tostring() we have declared name and age, In the console.Writeline we have techfunda and age value as 9 and incrementing the age value by i prints the value by incrementing the value in the output.

output

 

 Views: 5850 | Post Order: 18



Write for us






Hosting Recommendations