Breaking News

Editors Picks

Tuesday, June 21, 2011

as keyword in c sharp


as 

The as operator is used to perform certain types of conversions between compatible reference types . The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception

Example


class ClassA { }
class ClassB { }
 
class MainClass
{
    static void Main()
    {
        object[] objArray = new object[6];
        objArray[0] = new ClassA();
        objArray[1] = new ClassB();
        objArray[2] = "hello";
        objArray[3] = 123;
        objArray[4] = 123.4;
        objArray[5] = null;
 
        for (int i = 0; i < objArray.Length; ++i)
        {
            string s = objArray[i] as string;
            Console.Write("{0}:", i);
            if (s != null)
            {
                Console.WriteLine("'" + s + "'");
            }
            else
            {
                Console.WriteLine("not a string");
            }
        }
    }
}
/*
Output:
0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string
*/
 
 

Read more ...

sealed keyword c sharp


sealed 

The sealed modifier can be applied to classes, instance methods and properties. A sealed class cannot be inherited. A sealed method overrides a method in a base class, but itself cannot be overridden further in any derived class. When applied to a method or property, the sealed modifier must always be used with override 

It is an error to use a sealed class as a base class or to use the abstract modifier with a sealed class.
Structs are implicitly sealed; therefore, they cannot be inherited
Example


sealed class SealedClass
{
    public int x;
    public int y;
}
 
class SealedTest2
{
    static void Main()
    {
        SealedClass sc = new SealedClass();
        sc.x = 110;
        sc.y = 150;
        Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y);
    }
}
// Output: x = 110, y = 150
Read more ...

out keyword in c sharp


out 

The out and the ref parameters are used to return values in the same variables, that you pass an an argument of a method. These both parameters are very useful when your method needs to return more than one values.

The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword

The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.
public class mathClass
{
public static int TestOut(out int iVal1, out int iVal2)
{
iVal1 = 10;
iVal2 = 20;
return 0;
}
public static void Main()
{
int i, j; // variable need not be initializedConsole.WriteLine(TestOut(out i, out j));
Console.WriteLine(i);
Console.WriteLine(j);
}
}
Read more ...

ref keyword in c sharp


ref C#

The ref keyword causes arguments to be passed by reference. The effect is that any changes to the parameter in the method will be reflected in that variable when control passes back to the calling methodTo use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.An argument passed to a ref parameter must first be initialized

 For example:

class
 RefExample

{

    static void Method(ref int i)
    {
        i = 44;
    }
    static void Main()
    {
        int val = 0;
        Method(ref val);
        // val is now 44
    }
}
Read more ...

const keyword in c sharp

const C# 
The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable is constant, which means it cannot be modified. For example:

const int s = 0;
public const double gravitationalConstant = 9.673e-11;
private const string productName = "Visual C#";
The static modifier is not allowed in a constant declaration.
A constant can participate in a constant expression, as follows:

public const int c1 = 5;
public const int c2 = c1 + 100;

The readonly keyword differs from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, although a const field is a compile-time constant, the readonly field can be used for run-time constants,

Example
public class ConstTest 
{
    class SampleClass 
    {
        public int x;
        public int y;
        public const int c1 = 5;
        public const int c2 = c1 + 5;
        public SampleClass(int p1, int p2) 
        {
            x = p1; 
            y = p2;
        }
    }
    static void Main() 
    {
        SampleClass mC = new SampleClass(11, 22); 
        Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
        Console.WriteLine("c1 = {0}, c2 = {1}", SampleClass.c1, SampleClass.c2 );
    }
}
/* Output
    x = 11, y = 22
    c1 = 5, c2 = 10
 */
Read more ...

readonly keyword in c sharp


readonly


The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
http://i.msdn.microsoft.com/Hash/030c41d9079671d09a62d8e2c1db6973.gifExample


In this example, the value of the field year cannot be changed in the method ChangeYear, even though it is assigned a value in the class constructor

class Age
{
    readonly int _year;
    Age(int year)
    {
        _year = year;
    }
    void ChangeYear()
    {
        //_year = 1984; // Compile error if uncommented.
    }
}
You can assign a value to a readonly field only in
the following contexts: 

·  When the variable is initialized in the declaration, for example:
·         public readonly int s = 52;
·        For an instance field, in the instance
constructors of the class that contains the field declaration.
he readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants
:
Read more ...

what is static keyword in c#


static (C# Reference)

The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. 
The following class is declared as static and contains only static methods:
static class CompanyEmployee
{
    public static void DoSomething() { /*...*/ }
    public static void DoSomethingElse() { /*...*/  }
}
A constant or type declaration is implicitly a static member.
A static member cannot be referenced through an instance. Instead, it is referenced through the type name. For example, consider the following class
While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.
It is not possible to use this to reference static methods or property accessors.
If the static keyword is applied to a class, all the members of the class must be static.
Classes and static classes may have static constructors. Static constructors are called at some point between when the program starts and the class is instantiated.
  public class Employee
{
    public string id;
    public string name;
 
    public Employee4()
    {
    }
 
    public Employee (string name, string id)
    {
        this.name = name;
        this.id = id;
    }
 
    public static int employeeCounter;
 
    public static int AddEmployee()
    {
        return ++employeeCounter;
    }
}
 
class MainClass : Employee
{
    static void Main()
    {
        Console.Write("Enter the employee's name: ");
        string name = Console.ReadLine();
        Console.Write("Enter the employee's ID: ");
        string id = Console.ReadLine();
 
        // Create and configure the employee object:
        Employee e = new Employee (name, id);
        Console.Write("Enter the current number of employees: ");
        string n = Console.ReadLine();
        Employee.employeeCounter = Int32.Parse(n);
        Employee.AddEmployee();
 
        // Display the new information:
        Console.WriteLine("Name: {0}", e.name);
        Console.WriteLine("ID:   {0}", e.id);
        Console.WriteLine("New Number of Employees: {0}",
                      Employee.employeeCounter);
    }
}
    /*
    Input:
    sunil
    SU643G
    10
     * 
    Sample Output:
    Enter the employee's name: Matthias Berndt
    Enter the employee's ID: SU643G
    Enter the current number of employees: 10
    Name: sunil
    ID:   SU643G
    New Number of Employees: 11
    */






Read more ...

abstract keyword in c sharp


abstract

The abstract modifier is used in classes, methods and properties.
Abstract modifier is used when you want the class to be a base class for other classes.
Key points concerning abstract classes:
  • May not be instantiated.
  • May contain abstract methods and accessors.
  • Cannot be modified with the sealed modifier.
  • A non-abstract class derived from an abstract class must include actual implementations of all the inherited abstract methods and accessors
You may use the abstract modifier in methods and properties to serve the same purpose of not having implementations of it.
Key points concerning Abstract methods:
  • It is implicitly a virtual method.
  • May only be declared in abstract classes.
  • There is no method body since there is no implementation of it during declaration. 
    • public abstract void MyMethod();  // no {} after the signature
      
    • The actual implementation is provided by an overriding method which is of course of a non-abstract class.
    • The following modifiers are not allowed in an abstract method declaration: static, virtual and override.
    Abstract properties are similar to abstract methods except for declaration and invocation syntax. Key points concerning abstract properties:
    • May not be static
    • An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override method.

    An abstract class must provide implementation for all interface members.
    An abstract class that implements an interface might map the interface methods onto abstract methods. For example:
    interface I 
    {
       void M();
    }
    abstract class C: I 
    {
       public abstract void M();
    }
    

    Example

    In this example, the class MyDerivedC is derived from an abstract class MyBaseC. The abstract class contains an abstract method, MyMethod(), and two abstract properties, GetX() and GetY().
    // abstract_keyword.cs
    // Abstract Classes
    using System;
    abstract class MyBaseC   // Abstract class
    {
       protected int x = 100; 
       protected int y = 150;
       public abstract void MyMethod();   // Abstract method
    
       public abstract int GetX   // Abstract property
       {
          get;
       }
    
       public abstract int GetY   // Abstract property
       {
          get;
       }
    }
    
    class MyDerivedC: MyBaseC
    {
       public override void MyMethod() 
       {
          x++;
          y++;   
       }   
    
       public override int GetX   // overriding property
       {
          get 
          {
             return x+10;
          }
       }
    
       public override int GetY   // overriding property
       {
          get
          {
             return y+10;
          }
       }
    
       public static void Main() 
       {
          MyDerivedC mC = new MyDerivedC();
          mC.MyMethod();
          Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY);    
       }
    }
    

    Output

    x = 111, y = 161
    
Read more ...

Contact Us

Name

Email *

Message *