Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

C# Source Code for Beginners

This is the source code written based on the concepts explained in the Code Project C# Beginner's Article by Aisha Ikram Titled "Quick C#". This code should be helpful for the beginners to understand the following C# language features:

  • Program structure
  • Namespaces
  • Modifiers
  • Properties
  • Interfaces
  • Function parameters
  • Arrays
  • Indexers
  • Boxing and unboxing
  • Delegates
  • Inheritance and polymorphism

For more information about the Code Project article, look into http://www.codeproject.com/csharp/quickcsharp.asp

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using usethis;
//Based on the C# programming concepts explained in the CodeProject Article
//http://www.codeproject.com/csharp/quickcsharp.asp
namespace FirstCSharpConsole
{
sealed class Program //sealed means no class can be inherited from this class
{

static void Main(string[] args)
{
helloworld obj = new helloworld();
obj.myVal = 10; //set property
int a = 10;
obj.func(ref a);//Pass a by reference
Console.WriteLine(a); //a will be multiplied by 10

int m;
obj.outSomething(out m);
Console.WriteLine(m);//m is out returned in the prev method as 100

obj.varparams();
obj.varparams(0, 1, 2, 3);
obj.varparams(new int[] { 1, 2, 3 });

objIsSomething(obj);

square obj1 = new square();
obj1.length = 10; //set
obj1.breadth = 20; //set
obj1.draw(obj);
Console.WriteLine(obj1.length); //get
Console.WriteLine(obj1.breadth); //get

myShape obj2 = obj1 as myShape; //"as" returns null if obj1 is NOT myShape. else returns myShape
if(obj2==null)
Console.WriteLine("square is NOT myShape");
else
Console.WriteLine("square is myShape");

Console.WriteLine("Say Hi or Hello");
obj1.playWithSwitch();

//TODO: lock: Its just like a critical section and will be needed in multi threading code

//checked and unchecked: If the below block is not in unchecked it would have raised exception
//unchecked means telling the compiler not to check for any exceptions
unchecked
{
int unch = Int32.MaxValue;
unch= unch* 2;
}

//Delegates
demoDelegates d1 = new demoDelegates();
d1.perform(10, 20);

//Virtual Functions
square s1 = new splSquare();
s1.draw(obj1);

int k = 10;
object ko = k; //boxing: package into object
int j = (int) ko; //unboxing: unpack from object

}//end of Main

private static void objIsSomething(helloworld obj)
{
if (obj is object) //all objects derive from "object"
Console.WriteLine("helloworld is object");
else
Console.WriteLine("helloworld is not object");
}
}//end of class
}//end of namespace

namespace usethis
{
class helloworld
{
int setandget; //property variable
const int need2InitHereItself = 10; //direct init
readonly int canInitHereOrInCtor = 20; //direct init
readonly int willInitInCtor;

public helloworld()
{
willInitInCtor = 30; //indirect init
canInitHereOrInCtor = 25; //reinit can be done in ctor only
canInitHereOrInCtor = 26; //reinit can be done in ctor only
}

//property is myVal
public int myVal
{
set
{
setandget = value; //note that value is a keyword
}
get
{
return setandget;
}
}

//normal method
public void func(ref int temp)
{
Console.WriteLine(this.myVal); //get property
Console.WriteLine(this.canInitHereOrInCtor);
Console.WriteLine(this.willInitInCtor);
temp = temp * 10;


//try to set readonly var
//canInitHereOrInCtor = 6999; //will give a compiler error

//try to use pointer
//int* k = new int(); //will give a compiler error

//use unsafe to write pointer code.
//Note: Need to add /unsafe in compilng options
unsafe
{
int ki = 10;
int* k = &ki; //Note: NULL is not recognised in C#
}

//Array declarations
int[] a = new int[5]; //single dimensional array
a[3] = 10;

int[,] b = new int[5, 10]; //2D array
b[0, 3] = 20;

int[][] arrayofarray = new int[2][]; //*jagged* array
arrayofarray[0] = new int[4];
arrayofarray[1] = new int[] {1,12,15};//array whose array elements are inited

//foreach: can be used to iterate in array or collection
foreach (int iter in a)
{
Console.WriteLine(iter);
}

} //end of func

//demos usage of out param
public bool outSomething(out int x)
{
x = 100;
return true;
}

//unsafe method. just for illustration, not called anywhere
public unsafe void danger()
{
int ki = 10;
int* k = &ki;
}

public void varparams(params int[] arrs)
{
Console.WriteLine("number of elements in array are {0}", arrs.Length);
}
} //end of class

interface myShape
{
int length
{
get;
set;
}
int breadth
{
get;
set;
}
void draw(object shape);

}//end of interface

//implementation class for the interface
class square : myShape
{
int sqX;
int sqY;

//get and set interface vars implemented here
public int length
{
get
{
return sqX;
}
set
{
sqX = value;
}
}
public int breadth
{
get
{
return sqY;
}
set
{
sqY = value;
}
}

//implement interface methods
public virtual void draw(object shape)
{
Console.WriteLine("interface method draw implemented here (base class)");
}

public virtual void playWithSwitch()
{
string s = Console.ReadLine();
switch (s)//strings are allowed in c# unlike c++
{
//not having break will give a compiler error
case "hi"://this is allowed
case "hello": Console.WriteLine("Hello how r u? bye"); break;
case "how r u": Console.WriteLine("I'm good thanks.bye"); break;
case "bye": Console.WriteLine("bye and have a nice day"); break;
}
}
}

class splSquare : square
{
//override will override the base class method,
//new will stop overriding the base class method
//Unlike C++, without specifying override will NOT override the base class method
//Cannot have both new and override methods for draw
public override void draw(object shape)
{
Console.WriteLine("interface method draw implemented here (derived class)");
}

//base keyword calls base class method. method is not called. this is just for demo.
public override void playWithSwitch()
{
base.playWithSwitch();
}

}


//To demonstrate indexers
class shapes : CollectionBase
{
public void add(myShape shp)
{
List.Add(shp);
}

//indexer: Indexer is used to write a method to access an element from a collection,
//by straight way of using [], like an array.
//its like overloading []
public myShape this[int index]
{
get
{
return (myShape)List[index];
}
set
{
List[index] = value;
}
}
}

class demoDelegates
{
delegate int Operation(int val1, int val2);
public int add(int val1, int val2)
{
return val1 + val2;
}
public int subtract(int val1, int val2)
{
return val1 - val2;
}
public int perform(int val1, int val2)
{
Console.WriteLine("Do you want to + or -?");
string ch = Console.ReadLine();
Operation oper;
//Delegates: Enables to conditionally(and dynamically)select the method to be invoked
if (ch == "+")
oper = new Operation(add);
else
oper = new Operation(subtract);

Console.WriteLine(oper(val1,val2));
return 0;
}
}//end of class

} //end of namespace

CSharp and Java

I was reading through this wikipedia article which i think is the best article to read about the differences between the C# and Java. Here are the interesting differences I found:

* By Default all the methods in Java are virtual. C# doesn't have virtual by default, in fact the virtual methods should have another keyword new or override to specify if the method is overrided or not.
* C# allows pointers (within unsafe block) but Java doesn't
* C# can have all public classes in one file, but Java needs to have a public class in a file name and the filename and classname should match.
* C# implements get set properties as part of syntax. (Java, C++ obviously doesn't have this)
* In C# switch statement can also have strings (Java, C++ doesn't allow this)
* More discussion on data type differences can be found here
* C# supports operator overloading but Java does not

More to be updated...

* Checked exceptions are special kind of exceptions in java which are mentioned in the method header. The method header should have all the exceptions its going to throw, otherwise it would be a compiler error. C# doesn't have checked exceptions.
* JNI for java allows to call non-java code from java. Similarly C# has "Platform Invoke" (P/Invoke) which enables C# to call unmanaged code. P/Invoke can be used to call WIN32 APIs but not C++ libraries.
* .NET framework has .NET-COM bridge which allows to call COM components are .NET code.

ASP, .net and C Sharp: What I have learnt

* ASP is a Microsoft internet server technology which allows the developers to write server side script inline with HTML code.
code between is executed at the server. This will also do: <script language="VBScript" runat="server">
* CLR (Common Language Runtime) is the same as Virtual Machine for Java
* ASP.NET relies on .net framework and CLR which enables uses to write code in C# and other .net languages. ASP.NET is pre compiled(ASP is not) and is faster than ASP.
* ASP.NET discourages inline code blocks although it is supported.
* C# has similar concepts that Java has although there are many differences.
* C# has automatic garbage collection (which means that the objects need not be destructed in
code)
* There are no global variables in C#, every variable should belong to a class
* Duplicate variable names are not allowed in C#(unlike C and C++ where same names are alowed in different blocks)
* C# has a concept of namespaces and assemblies. assemblies are similar to Java packages.
* C# restricts only bool to be used in if conditions (no int is allowed in if stmt)
* C# allows pointers and devs can mark the pointer code as unsafe
* C# doesnt allow multiple inheritance
* C# has partial class keyword which can be used to break up class code in different files
* Generics and parametrized types are similar to templates
* Coalesce operator ("??") returns the first operator which is not null (eg a = b??0 assigns b to a)

//Hello world example in C#
public class ExampleClass
{
public static void main()
{
System.console.WriteLine("Hello World");
}
}