Windows Phone Developers

Wednesday, October 22, 2008

How to Create Classes in C#

C# Class Examples

A class can be created using the class keyword. A class can contain properties, variables, constants, events, methods, constructors, structs etc.

class ClsTea

{

//Variables

private string _locale;

private static string _brand;

// Property

public static string Brand

{

get

{

return _brand;

}

set

{

_brand = value;

}

}

//property

public string Locale

{

get { return _locale; }

set { _locale = value; }

}

private string[] brands = new string[12];

public string this[int index]

{

get { return brands[index]; }

set { brands[index] = value; }

}

}

A class can inherit implementation from one base class only. For example, ClsTea can Inherit from Class Beverages

class ClsTea : Beverages

A class can, however, implement more than one interface

Inheritance

Example

None

class ClsTea { }

Single

class ClsTea : Beverages { }

None, implements two interfaces

class ClsTea: IProduct, IRetail { }

Single, implements one interface

class ClsTea : Beverages, IRetail { }

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Download Microsoft C# Language Specification

The C# Language Specification is the authoritative source for C# grammar and syntax. It contains detailed information about all aspects of the language and many points not covered in the Visual C# product documentation. The C# 3.0 specification has been updated and merged with earlier versions into a single document.

The C# Language Specification is available in Microsoft Word format from the following locations:

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Creating DLLs (Dynamic Linked Libaries) using C#

There are three different types of output that can be generated out of a C# Console Assembly project

  • Windows Application
  • Console Application
  • Class Library

This can be specified in the General Application Settings of the Properties Window (Project à Properties [or] Right Click on the Project in Solution Explorer -- > Properties)


Visual Studio Project Settings


This can also be specified from command line-compiling as follows

csc /target:library /out:CSharpExample.DLL Program.cs ClsTea.cs


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Static Functions and Instance Members in C#

Static Class and Static Members in C#


Static classes are classes that do not contain instance members other than those inherited from Object, and do not have a callable constructor.

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.

Envirnoment class is a good example of a static class. You need not create a new instance of the class with new keyword to get access to its members. You can directly access its members as shown below

Console.WriteLine(Environment.MachineName);

Static members are not associated with a specific instance of a class. To call a static member, you qualify the static member with the class name.

For example, MyClass.StatMember

Because static members are not associated with object instances, they do not have access to non-static members (which are accessed through "this," which represents the current object instance).

Non-static members are called instance members because they are associated with individual object instances. Think of static members as belonging to the class and instance members belonging to instances of the class (that is, objects).

class ClsTea

{

public string Brand

{

get

{

return _brand;

}

set

{

_brand = value;

}

}

}

The above is a non-static member and can be accessed by an instance of the class as shown below:

ClsTea MyTea = new ClsTea();

MyTea.Brand = "Tata";

Console.WriteLine("My favourite tea brand is " + MyTea.Brand);

Qualifying the member with the name of the class like ClsTea.Brand = "Tata"; will throw an ‘An object reference is required for the nonstatic field, method, or property 'member'’ exception

A static member can be accessed as shown below

class ClsTea

{

private static string _brand;

public static string Brand

{

get

{

return _brand;

}

set

{

_brand = value;

}

}

}

ClsTea.Brand = "Tata";

Console.WriteLine("My favourite tea brand is " + ClsTea.Brand);

Here the Member is directly qualified using the Class Name (no instantiation is required)

Using the class objects to access a static member will throw an “Static member 'member' cannot be accessed with an instance reference; qualify it with a type name instead” error

ClsTea MyTea = new ClsTea();

MyTea.Brand = "Tata";

.NET What are Static Classes?, C# What are Static Classes?, .NET What are Static Functions/methods?, C# What are Static Functions/methods?, How to access a static member in C#, How to access an instance (non-static0 member in C#

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to get the return value from C# program (console application)

Check Return Values of C# Program from a Batch File

Main() is void (returns nothing) by default; however, it can be made to return integer values as shown below

if (args.Length == 0)

{

Console.WriteLine("No Arguments Passed");

return -1;

}

else

{

Console.WriteLine("Following are the arguments");

foreach (string arg in args )

{

Console.WriteLine(arg);

}

return 0;

}

The above program will return error value (-1) if it doesn’t have any arguments.

The return value will be stored in an Environment Variable ERRORLEVEL. By checking the value of this variable, we can conclude the successful execution of the program

Here is the DOS batch file to check the Environment Variable – ERRORLEVEL

@echo off

rem CSharpSample "sample"

CSharpSample

@if "%ERRORLEVEL%" == "0" goto success

:fail

echo Execution Failed

echo return value = %ERRORLEVEL%

goto finally

: success

echo Execution Succeded

echo return value = %ERRORLEVEL%

goto finally

: finally

Pause

The above program returns error.

Passing a parameter to the program as shown below returns success.

@echo off

CSharpSample "sample"

@if "%ERRORLEVEL%" == "0" goto success

:fail

echo Execution Failed

echo return value = %ERRORLEVEL%

goto finally

: success

echo Execution Succeded

echo return value = %ERRORLEVEL%

goto finally

: finally

Pause




Return Value Succeeded

Error Value Returned from C# program
See also:

Output Parameters in C# (.NET)

How to Return Multiple Values from a VBA Function

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

C# Console Application – Pause for User Input / Pause Command in C# Console Application

In some cases you may require to pause for the user input or display a message to the user and prompt him to continue by pressing the key.

ReadKey does the trick. It obtains the next character or function key pressed by the user.

Console.WriteLine("Press any key to continue...");

Console.ReadKey(true);

If you want the key to be displayed on user window, you can set the parameter to be false. You can also get the pressed key using as ConsoleKeyInfo shown below

Console.WriteLine("Press any key to continue...");

System.ConsoleKeyInfo KInfo = Console.ReadKey(true);

Console.WriteLine("You have pressed :" + KInfo.Key.ToString());

Press any key to continue in C#, C# Console Application Wait, Wait for user input in C# Console Application, C# Console Application, C# ConsoleKeyInfo, C# KeyPress in Console Application

Press any key to continue in .NET, .NET Console Application Wait, Wait for user input in .NET Console Application, .NET Console Application



C# Console Application Wait Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Command Line Arguments in C#

C# Command Line Arguments

The parameter of the Main method is a String array that represents the command-line arguments. Check for the existence of the arguments by testing the Length property and iterate through the array to get the arguments

if (args.Length == 0)

{

Console.WriteLine("No Arguments Passed");

}

else

{

Console.WriteLine("Following are the arguments");

foreach (string arg in args )

{

Console.WriteLine(arg);

}

}

The arguments can also be accessed as zero-based array

Multiple arguments are split by delimiters (space). If you want to send a string like “c:\my documents\”, enclose it within double quotes.

Command Line Arguments in C#, C# Command Line Arguments, Command Line Argument Arrays in C#, Accessing command line arguments as an array using C#



Command Line Arguments in C#

See also:

Visual Basic Command Line Arguments Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon