cookieChoices = {};
Showing posts with label Console and Basics. Show all posts
Showing posts with label Console and Basics. Show all posts

Friday, 29 November 2013

C Sharp Language Basics

Integral Types

DataType
Size
.Net(CTS)
Comments
byte
1
System.Byte
0 - 255 It is Unsigned
sbyte
1
System.SByte
-128 to 127 - Signed
short
2
System.Int16

ushort
2
System.UInt16

int
4
System.Int32

uint
4
System.UInt32

long
8
System.Int64

ulong
8
System.UInt64



 Floating Types
float
4
System.Single
Has up to 8 digits after decimal
double
8
System.Double
Has up to 16 digits after decimal




Deciaml
16
System.Decimal
Has fixed 28 digits after decimal and its fixed


 Other DataTypes
string *
4
Systring.String
Uses Unicode Charset
char
2
Systring.Char
Uses Unicode Charset
bool
1
Systring.Bool

object *

System.Object
Generic Datatype


 Variable Declaration Syntax:
int a,b;
 int a=10, b=20;
·         A local variable declared must be explicitly initialized before used in an expression otherwise gives an compilation error


 using System;
class Program
{
public static void Main()
 {
int n = 256;
 byte b;
unchecked //Overflow checks are not done…
 {
b = (byte) n;
 Console.WriteLine(b);
}
checked //Overflow checks are done…
 {
b = (byte) n;
Console.WriteLine(b);
 }
 double dbl = 0.6D;
//0.6 float f = 0.6F;
decimal dec = 0.6M;
//float and decimal requires casting dec = 10;
 //Integer to decimal //f = dec;
//Invalid //Valid in VB //dec = f;
 //Invalid f = (float) dec;
//In VB-Implicit dec = (decimal) f;
//“decimal” should be explicitly casted to every other type if required.
 string s = "Demo";
char c = 'S';
//In VB - "S"c
 //int to char. n = c;
//In VB: n = AscW(c)
 /*c = n; invalid */

 c = (char) n;
//In VB: c = ChrW(n)
//bool – int /anydatatype explicit or implicit casting is not allowed either direction
//string to int s = "100";
 n = (int) s;
//Invalid – String cannot be casted n = int.Parse(s);
//if failes throws, FormatException bool bln = int.TryParse(s, out n);
//n = (int) s; //Invalid //int to string s = n.ToString();
//s = (string) n //Invalid
//long to float - Same as VB
long lng = 10L;
f = lng;
//because range of long is smaller than float
 lng = (long) f;
object obj = n; //Boxing
n = (int) obj; //Unboxing

 var n = 0
// n is of type
int var s = "Hello"
// s is of type string
const double PI = 3.14;
byte b1, b2, b3;
 b1 = b2 = 10;
//In VB it is not valid b1 = b2 + b3;
//Compilation Error
//if byte, short or char variables are used in an expression they are automatically raised to the rank of int.
 b1 = (byte) (b2 + b3);
Console.WriteLine(3 / 2); //Result - 1
                Console.WriteLine(3.0 / 2); //Result - 1.5
n = 10;
int m = n++;
//m=n; n=n+1 - Post Increment
Console.WriteLine(n + " " + m);
m = ++n; //n=n+1; m=n - Pre Increment
Console.WriteLine(n + " " + m);
//?: Conditional Operator (VB: IIf)
int max;
max = n > m ? n : m; //?: Operator
           //Enum Sample
n = 2; //n is int
WeekDay wd = WeekDay.Sat;
wd = (WeekDay) n;
                //Explicit
                //n = wd;
                //Invalid n = (int) wd;
//Explicit - In VB.NET it‟s not required
 }
 }
enum WeekDay : int //WeekDay is subtype of int
 {
Sun=1, Mon, Tues, Wed=5, Thus, Fri, Sat
 }

Enum can be subtype of any integral type only

OverflowException.

Operators Arithmetic
+, -, * , / , % (mod) (Power operator is missing)
Logical Operators
^ (XOR), !(NOT) && (VB-AndAlso) , || (VB-OrElse)
Ternary Operator
?:
String concatenation
+ (VB-&)
Increment, decrement
++ , --
Bitwise
<< , >>, & , | , ~ (complement/negation)
Relational
= = , != , < , > , <= , >=
Assignment
= , += , -= , *= , /= , %= , &= , | = , ^= , <<= , >>=
Type information
is , sizeof , typeof, as
Indirection and Address
* , -> , [] , &

Note for VB.NET Programmers:

In C# the arithmetic operator „/ ‟ is the same for both floating point and integer datatypes and the result depends on the operands.

Control Statements
if-statement: if (BooleanExpression) { statement; } else if (Boolean-Expression) { statement; } else { statement; }
Switch Statement int expr; switch (expr) //expr can only integral type / char / string { case 0: //value of case must be a constant. statements; goto default; // or break can be used. case 1: case 2: statements; break; //break must be preset after every case with statements default: statements; break; //break must be present after default also. }
while…..loop while (BooleanExpression) { Statements; }
do { Statements; }while (BooleanExpression);



for and foreach statements

for ( initializer; condition; iterator )
{
statements;
}

foreach (DataType identifier in <Array or Collection>) {
embedded-statements;
}

 for (int i = 0; i < 10; i++)
 {
if (i == 7) break;
 if (i == 3) continue;
 Console.WriteLine(i);
}

 foreach (string s in args)
Console.WriteLine(s);
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (i == j) break;
Console.WriteLine(i + " " + j);
}
}
}
}

·         “break” and “continue” statements can be used in “for” and “while” loops.
·         C# doesn‟t support “With” statement

Working with Arrays
1.       Single-Dimensional Arrays
int [] myArray = new int [5];
string []myStringArray = new string[5];
 When you initialize an array upon declaration, it is possible to use the following shortcuts:
 int[] myArray = {1, 3, 5, 7, 9};
string[] weekDays = {"Sun", "Sat", "Mon", "Tue"};
It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable.
For example: int[] myArray;
 myArray = new int[] {1, 3, 5, 7, 9}; // OK
 myArray = {1, 3, 5, 7, 9}; // Error
 weekdays = new string[] {“Sunday”, “Monday”, “Tuesday”};
2. Multidimensional Arrays
int[,] myArray = new int[4,2];
Also, the following declaration creates an array of three dimensions, 4, 2, and 3:
int[,,] myArray = new int [4,2,3];
You can initialize the array upon declaration as shown in the following example:
 int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
You can also initialize the array without specifying the rank:
 int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};
 If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:
int[,] myArray; myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}}; // OK
 myArray = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error
class Program
 {
static void Main(string[] args)
{
 int[] ar = new int[ ] {1,2,3,4};
 Console.WriteLine(ar.Length);
Console.WriteLine(ar.Rank); //Prints Number of Dimensions in array.
 foreach (int n in ar)
Console.WriteLine(n); //To increase the size of existing array and also retaining data in it. i.e equivalent of Redim Preserve in VB.
 int[] temp =ar;
ar = new int[temp.Length +1];
 Array.Copy(temp, ar, temp.Length);
temp=null;
foreach (int n in ar)
Console.WriteLine(n);
}
 }








 Working with Methods
using System;
 class Program2
{
public static void Main()
 {
 int res = Add(10, 2);
 int[] mar = { 1, 2, 3, 4 };
 res = Add(mar);
res = Add();
 res = Add(1, 2, 3, 4, 5);
 res = Add(1, 2, 3, 4, 5, 6);
 res = Add(1, 2, 3, 4, 5, 6, 7); //Pass by value or reference example…. int n1, n2, n3; n1 = n3 = 10;
Foo(n1, out n2, ref n3); Console.WriteLine(n1 + " " + n2 + " " + n3); }
 //Pass by value and reference example static void Foo(int a, out int b, ref int c)
{
 a++; b = 20; c++;
 }
static int Add(int a, int b)
 {
return Add(a, b, 0);
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
static string Add(string s1, string s2)
{
return s1 + s2;
}
static int Add(params int[] ar)
{
int sum = 0;
foreach (int n in ar)
sum += n; return sum;
}
}


·         Out parameter must be initialized in the method and are generally used in situations where we want to return more than one value from the method.
·         C# doesn’t support Optional parameters with default values and Named arguments.

static int Foo(int a) { if (a != 0) return a; }

If a method has return type anything other than “void”, all code paths in it must return a value.
The example gives compilation error because if a==0 nothing is mentioned as return value.



General Points; For String: @"C:\Demo" or "C:\\Demo", "This is \"Quoted\" String"

Thursday, 28 November 2013

Console Application Introduction



Agenda:
1. Solution and Project in VS.NET
2. Importance of Main – Entry point of an application
3. Different forms of Main


1. Solution is a Collection of Projects. One Solution can have many projects and every project added to the solution can of same language or different language.
2. The Solution file has the extension .sln.
3. A Project is a collection of files including Source Code (.vb/.cs), Resources(.resx), Configuration(.config) files etc…
4. The project file has the extension .vbproj or .csproj
5. A project when build (compilation + linking) generates an EXE/DLL as output, which is called as PE.

Time to create our first MS.Net application: Goto File à New à Project à Select Visual C# on Left and Console Application on right. Name = “FirstConApp” – This is the project name Location = “C:Projects\\”.
class Program
{
public static void Main()
 {
Console.WriteLine("Hello C#");
                }
}

To Build the Solution Goto Menu: Build à Build Solution (Ctrl + Shift + B) To Run the Application

1. Debug à Start Debugging (F5) – Here we can use break points and debug the application.
2. Debug à Start Without Debuggin (Ctrl + F5) - We can see the output in console window.

When the project is build the following output file is generated: Drive:\...\<ProjectName>\bin\debug\<ProjectName>.Exe Note: In VS.NET 2008, at the time of creating a project we can specify the Framework Version to be used which can be either 2.0, 3.0 or 3.5.


Mostly the console based applications are developed in situations where the application should either run as a top level process or as child process (invoked from another parent process). Commandline Arguments: This is the best way of providing input to the console based application.
using System;
class Program
{
static void Main(string[] args) 'args is an array of commandline arguments.
 {
Console.WriteLine("Hello " + args[0]); 'args(0) is the first command line argument.
}
}



To give Commandline arguments in Visual Studio: View à Solution Explorer à Select Project à Right Click à Properties à Debug Tab à Command Line Arguments à Provide string separated by space (Args1 Args2 Args3) Or Give at command prompt in console window Drive:\. . . \ ProjectName\ in\debug\<ProjectName>.exe Args1 Args2 Args3

Return value of Main:
using System;
class Program
{
static int Main(string[] args) 'args is an array of commandline arguments.
                {
Console.WriteLine("Hello " + args[0]); 'args(0) is the first command line argument.
                                return 0;
                }
 }



1. When the application is not used as child process, the return value of main is not usefull because what ever may return the value, main ends the application ends and OS will clean all the memory allocated to it.
2. The return value of Main is used by the current application to communicate its state to the parent process when the application terminated. The Integer return value can be predefined with some meaning and the same will be used by the parent process to know the state of child process which terminated. The return value of an application is called as EXIT CODE of the application.

Multiple Startup classes in one project

One Project can have multiple modules but only one of many modules with valid Main can be treated as Startup or Entry Point of the application. To Add another File to Project: Goto Solution Explorer à Right Click on Project à Add à Class
using System;
class Program2
{
static void Main()
{
Console.WriteLine("Hello Program2");
}
 }
To Set Startup Object: View à Solution Explorer à Project à Right Click à Properties à Application Tab à Starup Object à Select Class whose Main should be used as entry point. Note: The class declared as startup object cannot have more that one form of Main which are valid for entry point. All classes in the project can be placed in either in same file or in different files. In either case the compiler is going to compile them together. i.e. for a dotnet language compiler files cannot be used as boundries and all the files are compiled together as one unit.

 To open a closed Solution / Project: File à Open à Project / Solution à Give the Path of .sln file.



 To develop an application without using VS.NET (compiling at command prompt)

1. Open Notepad
2. Write the code as given above and Save as C:\Demo.CS
3. Goto Start à Programs à Microsoft Visual Studio 2008 à Visual Studio Tools à VS 2008 Command Prompt (so that the directory of MS.NET Framework is set in “PATH”)
4. CSC.EXE C:\Demo.CS => Generates Demo.exe
5. Run Demo.exe


Framework Folder: C:\Windows\Microsoft.Net\Framwork\V3.5.XXXX\