C Sharp syntax

From Wikipedia, the free encyclopedia

The correct title of this article is C# syntax. The substitution or omission of a # sign is because of technical restrictions.
Main article: C#

The syntax of the C# is a set of rules which defines how to write and interpret code. This article contains new features of the upcoming C# 3.0. These features are not yet officially released.

Contents

[edit] Basics

[edit] Identifier

An identifier is the name of an element in the code. There are certain naming conventions that you should follow when you are naming elements yourself.

An identifier can:

  • start with a "_".
  • contain both upper case and lower case letters.

An identifier cannot:

  • start with a numeral.
  • start with a symbol, unless it is a keyword (check Keywords).
  • have more than 511 chars.

[edit] Keywords

Keywords are reserved words that you cannot use when you are naming your own variables.

However there is one way to use keywords as your identifier. Add an @ (at) in front of the keyword you want to use.

Table of keywords

string @out; //Now you can use the keyword as an ordinary identifier.

Note: from is still a keyword when you use it in your code.

[edit] Variables

Variables are places for storing values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.

Declare

int MyInt;         // Declaring an uninitialized variable.
MyInt = 7;         // Initializing a previously uninitialized variable

Initialize

int MyInt = 35;    // Declaring and initializing
MyInt = 106;       // Assigning to an already declared variable.

C# 3.0 introduced type inference, allowing the declaration's type to be replace by the keyword var, if its actual type can be determined by an initializer. This reduces repetition, especially for types with multiple generic type-parameters, and adheres more closely to the DRY principal.

var MyChars = new char[] {'A', 'Ö'}; // or char[] MyChars = new char[] {'A', 'Ö'};
 
var MyNums = new List<int>();  // or List<int> MyNums = new List<int>();

[edit] Data types

[edit] Primitive types

Primitive Types
Type Name BCL Equivalent Value Range Size
sbyte System.SByte integer -128 through 127 8-bit (1-byte)
short System.Int16 integer -32,768 through 32,767 16-bit (2-byte)
int System.Int32 integer -2,147,483,648 through 2,147,483,647 32-bit (4-byte)
long System.Int64 integer -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807 64-bit (8-byte)
byte System.Byte unsigned integer 0 through 255 8-bit (1-byte)
ushort System.UInt16 unsigned integer 0 through 65,535 16-bit (2-byte)
uint System.UInt32 unsigned integer 0 through 4,294,967,295 32-bit (4-byte)
ulong System.UInt64 unsigned integer 0 through 18,446,744,073,709,551,615 64-bit (8-byte)
decimal System.Decimal signed decimal number -7.9228162514264337593543950335 through 7.9228162514264337593543950335 128-bit (16-byte)
float System.Single floating point number 32-bit (4-byte)
double System.Double floating point number 64-bit (8-byte)
object System.Object .NET object variable
bool System.Boolean Boolean true or false 1-byte
char System.Char single Unicode character 16-bit (2-byte)
string System.String string of characters variable

[edit] User-defined types

class Hour
{
   public Hour()
}

[edit] Inheritance

A class can inherit another and get the same variables and methods as the base class.

class Mammal
{
        public Mammal()
        {
 
        }
}
 
class Horse : Mammal //Class Horse inherits class Mammal and contains all of its methods, properties and indexers.
{
        public Horse : base()
        {
 
        }
}

[edit] Structures

Commonly just known as Structs. The syntax of a struct is similar to that of a class, but a struct is a value type and therefore does not refer to an object on the heap.

struct Hour
{
   private int hours;      //Field
   private int minutes;    //Field
   private int seconds;    //Field
 
   public Hour(int hours, int minutes, int seconds)    //Constructor
   {
      this.hours = hours;
      this.minutes = minutes;
      this.seconds = seconds;
   }
}

Primitive types like int and double are structures, but strings and arrays are classes. ---

[edit] Enumerations

Enumerations, or simply Enums, are user-defined types which are used to contain variables with numerical values.

Code

enum Season
{
   Spring, Summer, Autumn = 2, Winter
}

Declaring and using

Season current = Season.Summer; //Declaring an enumerator and initiating it with Summer (value 1).
 
current++; //Raising currents value with one. Now it will contain value 2 and be Autumn.

[edit] Delegates

[edit] More

[edit] Classes and Structs

[edit] Constructor

A constructor is a method within a class or structure which is called when an instance is created. A constructor is named after its class or structure, is always public, does not have any return type (not even void), and can take parameters.

class Employee
{
   //Constructor
   public Employee(string Name, int Age, Role Role)
   {
       name = Name;
       age = Age;
       role = Role;
   }
 
   //Fields being initiated within the constructor.
   private string name;
   private int age;
   private Role role;
}

There are some differences between methods in classes and structures. Those are:

  • Classes: You do not need to create a standard constructor. The compiler generates one automatically.
  • Structures: The compiler does not generate a standard constructor. You need to create one yourself.
  • Classes: You do not have to initiate fields within the constructor. If you don't initiate a field it will automatically be assigned null or a numerical value.
  • Structures: You must write code to initiate.

If you initiate the fields when you declare them, then you do not have to initiate them in the constructor.

[edit] Finalizer

A finalizer is called when an object, or instance, has been collected by the garbage collector. It is defined almost exactly like a constructor. The only difference is that you write a '~' before the name and that it cannot take any parameters.

Code:

class Employee
{
   //Destructor
   public ~Employee()
   {
       Console.WriteLine("Customer disposed."); //Is executed when object is being collected by the GC.
   }
}

The order in which finalizers run is not deterministic.

[edit] Method

Methods are pieces of code equivalent to a procedure, function or subroutine.

Methods can take parameters and also return values.

A method without parameters and return-type

class ExampleClass
{
    public void WriteMessage() //Void = Nothing to return
    {
        Console.WriteLine("HelloWorld"); //Calling another method. In this case Console.WriteLine().
    }
}

A method with parameters and return-type

class ExampleClass
{
    public double DivideByTwo(double Number) //The function returns a value of type double
    {
        return Number/2;
    }
}

Calling a method

double result = DivideByTwo(20); //Divide 20 by 2 and return value to variable result;

Other types of methods:

[edit] Field

A field is a variable declared and shared within a class or struct.

[edit] Properties

[edit] Indexers

Indexers are properties that take arguments.

Indexers have the name "this" and have a set of arguments in brackets.

A basic class that has a indexer

class ExampleClass
{
    private int[] data = new int[100];
 
    public int this[int Index] //Indexer
    {
         get
         {
             return this.data[Index]; //Arguments in brackets are locals in the properties get and set code   
         }
         set
         {
             this.data[Index] = value;
         }
    }
}

A method that uses a indexer

public void UseIndexer()
{
     ExampleClass Tester = new ExampleClass();
     Tester[5] = 6;
     Console.Write(Tester[5]);
}

[edit] Modifiers


[edit] Inheritance

Classes can inherit another. In fact all types inherit the class Object.

Classes...

  • can only inherit one base class and through that one another.
  • can implement multiple interfaces.

Structures/Struct...

  • cannot inherit.

Interfaces...

  • can inherit other interfaces.

[edit] Classes

[edit] Interfaces

Interfaces are only describing the form of one or many methods: name, modifiers, return-type and parameters. You will need to implement these methods with code when you're inheriting it. Interfaces provide a means of defining the shared features of otherwise disparate classes.

interface IMyInterface
{
    string Text{get; set;} //Property
    char this[int index]{get; set;} //Indexer
}

A common naming convention is that a name of an interface begins with a capital 'i'.

[edit] Generics

see generic programming.

With generics you can write more type-safe code and tell that only a specific type is allowed.

[edit] Type-parameter

You declare a

[edit] Generic classes

This is what a generic class looks like.

class List<T> //Class with type-parameter.
{
    private T[] array; //An array field taking a type-parameter.
    public List(params T[] items)
    {
        array = items;
    }
}

Note: This is not the real code for the real List generic class.

//Declaring a List<T> with type string. Now it can only take strings or else the debugger will complain.
    List<string> list = new List<string>("house", "car", "wife");

How it works:
The compiler will automatically replace every T in the code with the type you want to replace it with. In this case a string.

[edit] Generic methods

Methods can also get type-safe.

class List<T> //Class with type-parameter.
{
    public T Find(T x)
    {
        //Some code
    }
}

Note: This is a bad example but you get the idea.

string value = myList.Find("car");

[edit] LINQ

Main article: LINQ

[edit] External links