+ All Categories
Home > Documents > c_basics

c_basics

Date post: 12-Nov-2015
Category:
Upload: kotirama
View: 259 times
Download: 4 times
Share this document with a friend
Description:
basis in c
Popular Tags:
52
.Net C# Data Types Data is physically stored inside cells of memory. This memory could be physical memory (Hard disk ) or logical memory (RAM). Any cell of memory is represented with a unique address. This address is more than some combination of numbers or symbols. C# language provides for practically all the data types . These types can be divided in three categories: value types, reference types and pointer types. There are some more basic concepts to be learnt before the discussion of the data types. This is about variables and constants. A Variable is a named cell of memory used for data storage . A Variable value can be changed anytime. Every variable must have a type and this type must be set before it is used. Qualifying a variable with a type is called as declaration of variable. The type of a variable is the most important aspect and it defines the behavior of variable. All variables can be divided into seven main categories depending on the context of usage: 1. Static variables 2. Variable of instance 3. Array's elements 4. Parameters given by reference 5. Parameters given by value 6. Returned values 7. Local variables. Static Variables will be alive throughout the life of a program. It can be declared using static modifier. An Instance variable is a variable declared without static modifier. Usually it is declared inside a class or structure definition. Parameter Values can be viewed as input parameters into methods: public static void Sum(int a, int b) { Console.WriteLine("The sum of elements {0} and {1} is {2}",a,b,a + b); } This code writes in console values of variables a, b and their summary value. Now if the values of these parameters are modified inside the method, this change will not be reflected inside the main function. It
Transcript

.Net C# Data Types

Data is physically stored inside cells of memory. This memory could be physical memory (Hard disk) or logical memory (RAM). Any cell of memory is represented with a unique address. This address is more than some combination of numbers or symbols. C# language provides for practically all the data types. These types can be divided in three categories: value types, reference types and pointer types. There are some more basic concepts to be learnt before the discussion of the data types. This is about variables and constants. A Variable is a named cell of memory used for data storage. A Variable value can be changed anytime. Every variable must have a type and this type must be set before it is used. Qualifying a variable with a type is called as declaration of variable. The type of a variable is the most important aspect and it defines the behavior of variable. All variables can be divided into seven main categories depending on the context of usage:1. Static variables2. Variable of instance3. Array's elements4. Parameters given by reference5. Parameters given by value6. Returned values7. Local variables. Static Variables will be alive throughout the life of a program. It can be declared using static modifier. An Instance variable is a variable declared without static modifier. Usually it is declared inside a class or structure definition. Parameter Values can be viewed as input parameters into methods:public static void Sum(int a, int b){ Console.WriteLine("The sum of elements {0} and {1} is {2}",a,b,a + b);}

This code writes in console values of variables a, b and their summary value. Now if the values of these parameters are modified inside the method, this change will not be reflected inside the main function. It is because the compiler creates copies of them when it passes them as value types. This ensures that their original values are not modified. Instead if one wants to modify the parameter variables inside the function, C# has something called Reference variables. Reference variables also have a modifier out which can be used before their type. Look at the following example:public static void SumRef(ref int a, ref int b){ a = 4; b = 6; Console.WriteLine("The sume of elements {0} and {1} is {2}",a,b,a + b);}

Now this method modifies the value of variables a and b with values 4 and 6. These values are retained even after the execution of the function gets completed.If the parameters need to be returned then they can be qualified with out modifier or as returned parameter in method definition. Here is an example of both of them, in which both of them return the same value:public static int SumOut(int a, int b, out int sum1){sum1 = a+b;Console.WriteLine("The sum1 of elements {0} and {1} is {2}",a,b,a+b);return sum1;}

In main function it must be called in the next manner:int sume ;sume = SumeOut(2,2, out sume);Constants in C#:Constant type of data cannot be changed. To declare a constant the keyword const is used. An example for the constant declaration is: const double PI = 3.1415;Values types in C#:Value type stores real data. When the data are queried by different function a local copy of it these memory cells are created. It guarantees that changes made to our data in one function don't change them in some other function. Let see at a simple example:public class IntClass{ public int I = 1;}Here we have simple class that contains only one public data field of integer type. Now have a look on its usage in main function:static void Main(string[] args){// test classint i = 10;int j = i;j = 11;IntClass ic1 = new IntClass();IntClass ic2 = ic1;ic2.I = 100;

Console.WriteLine("value of i is {0} and j is {1}",i,j);Console.WriteLine();Console.WriteLine("value of ic1.I is {0} and ic2.I is {1}",ic1.I,ic2.I);Console.WriteLine();}

Reference Types in C#: In the above example, assume that First we have two value type i and j. Also assume that the second variable is initialized with the value of the first one. It creates new copy in memory and after it the values of these variables will be next:i = 10;j = i; There are a few more things written in the above example for explaining the Reference Types in C#. At first, the variable ic1 of IntClass is created using dynamic memory allocation. Then we initialize the variable ic2 with value of ic1. This makes both the variables ic1 and ic2 referring to the same address. If we change a value of ic2, it automatically changes the value of ic1. Now, over to the discussions about the important value types used in C#. The category simple types contains some predefined or system types that also are commonly used in other programming languages. It contains integer types: byte, Sbyte, Long, Ulong, Short, Ushort, int, Uint. These common types differs only range of values and sign. Next simple type is character type. To declare a variable of this type need use keyword char. It can take values of characters or numbers as 16-digit symbol of the type Unicode. The Boolean type has only two values: true, false. But these values cannot be assigned with a 0 or 1 as in C++ language. Next category of simple types is floating point types. It contains two types float and double. Float type can get values in range from 1.5*10-45 to 3.4*1038. Double type has range of values from 5.0*10-324 to 1.7*10308. A structural value types are struct and enum. Struct is a the same as class but it uses real values not references. The following code snippet contains the definition for struct:struct Point3D{public float m_x;public float m_y;public float m_z;

public float [] GetArray(){float [] arr = new float[3];arr[0] = m_x;arr[1] = m_y;arr[2] = m_z;return arr;}}

The above is declaration for a simple structure of real 3D point. As you see a class declaration looks very similar to the struct except that the class also has a constructor.

Enumerated types can be used to create some set of identifiers that can have values of simple type. Let us see at example of enum type:public enum Days{Monday,Tuesday,Wensday,Thursday,Friday,Saturday,Sunday}

In example there are enum that has days of week names. The values of days by default are in range from 0 to 6.Common types in C#: Object in C# language is universal; it means that all supported types are derived from it. It contains only a couple of methods: GetType() - returns a type of object, ToString() returns string equivalent of type that called.Next type is class. It is declared in the same manner as structure type but it has more advanced features.Interface is an abstract type. It is used only for declaring type with some abstract members. It means members without implementations. Please, have a look at piece of code with a declaration for a simple interface:interface IRect{int Width{get;set;}

int Height{get;set;}

int CalculateArea();}

The members of interface can be methods, properties and indexers. Next reference type to be dealt is delegate. The main goal of delegate usage is encapsulation of methods. It most like at pointers to function in C++. String is common type that is used in almost all programming languages of high level. An example of string declaration and initialization: string s = "declaration and init"; The last very used reference type is array. Array it is set of elements that have the same type. Array contains list of references on memory cells and it can contain any amount of members. In C# there are three types of arrays: one-dimensional, two-dimensional and jagged array. So, this covers almost all types used in C#. All these types can be cast to another type using special rules. An implicit casting can be done with types when values of variables can be converted without losing of any data. There is special type of implicit casting called boxing. This enables us to convert any type to the reference type or to the object type. Boxing example:// boxingchar ch = 'b';object obj = ch;Console.WriteLine("Char value is {0}",ch);Console.WriteLine("Object value is {0}",obj);Console.WriteLine();

This piece of code prints the same values of integer type variable and object type variable. The opposite process to the boxing is un-boxing. An example for un-boxing is as follows.// unboxingfloat q = 4.6f;object ob = q;Console.WriteLine("Object value is {0}",ob);float r = (float)ob;Console.WriteLine("Float value is {0}",r);

So, it is main item of common data type creating and using. All sources are attached. To compile and run it need to run .NET command line. Just type: csc DataTypes.cs. It creates DataTypes.exe that can be run as standard executable file..Net C# Tutorial Intermediate Language - MSIL

Microsoft Intermediate Language (MSIL) is a platform independent language that gets compiled into platform dependent executable file or dynamic link library. It means .NET compiler can generate code written using any supported languages and finally convert it to the required machine code depending on the target machine. To get some clarity in this language we need to write some code. In this tutorial we?ll use a very simple piece of source code in C# .Net. Now we need to compile this code using csc command in Microsoft .NET on the command line. To do this, please type next string: csc ILSample.cs. After it compiler will create an executable file named ILSample.exe. After this type the command called ILDasm. It will open application called Intermediate Language Disassembler. In file menu choose open and find our executable file.This application opens our assembly showing all structural units viz., classes, methods, data fields and all global and local application data. Now if you click on the method it shows code in intermediate language. This code is most like at language with independent set of instructions.

public double GetVolume(){ double volume = height*width*thickness; if(volume Assembley =>Class Loader =>Jit Compiler =>Manged Native Code=>Execution. The above is the order of compilation and execution of programs. Once a program is written in a .Net compliant language, the rest all is the responsibility of the frame work.Methods and properties

Any class in an object-oriented language has method and property members. These are the places where the actual business logic or functionality is written and executed. This tutorial explains how to create and use methods and properties in C#.

C# Methods:

Method is object-oriented item of any language. All C# programs are constructed from a number of classes and almost all the classes will contain methods. A class when instantiated is called an object. Object-oriented concepts of programming say that the data members of each object represent its state and methods represent the object behavior.

Method Signature in C#:

Each method is declared as follows: Return-type methodname ( Parameterslist );

For better understanding of methods let consider following example. We have a class Man. It can have many fields like that:

public class Man{ public Man(){} private int m_old; private string m_name; public string WhatIsYourName() { Console.WriteLine(m_name); return m_name; } public string HowOldAreYou() { Console.WriteLine(m_old.ToString()); return m_old; }}

The private members m_old and m_name define some state of objects that can be created as instances of our class. Also the class Man has two methods, which serve some of our requests. Method string WhatIsYourName() writes current object?s name to the console and returns it, and the second one similar to first return age of man and also writes an output to the console.

The return type in the example above returns strings, which is an in-built data type. The methods can also return any generic C# type or any custom types created by us.

Passing Parameters to Methods in C#:The input parameters can be passed in two ways.

Value type

Reference type.

If parameters are passed as value types a new copy of it will be created and passed inside the function. If they are created as reference types, only the address of the parameters will be passed.

See next example:

public int CalculateBirthYear(int year){ int b = year - m_old; Console.WriteLine("Birth year is {0}",b); return b;}

If input parameter pass as reference type it must use keyword ref, in that way we operate with the same cell in memory. That?s mean it can be changed inside any method. A small example for a parameter passed by reference is:

public int CalculateBirthYear(ref int year){ int b = year - m_old; Console.WriteLine("Birth year is {0}",b); return b;}

Now, the function CalculateBirthYear can even modify the value of year as it is passed by reference.

Output Parameters in Methods:

The return values in any function will be enough for any one if only one value is needed. But in case a function is required to return more than one value, then output parameters are the norm. This is not supported in C++ though it can be achieved by using some programming tricks. In C# the output parameter is declared with the keyword out before the data type. A typical example is as follows.

public void CalculateBirthYear(ref int year, out int birthyear){ int b = year - m_old; Console.WriteLine("Birth year is {0}",b); birthyear = b; return;}

Strictly speaking there is no difference between ref and out parameters. The only difference is that the ref input parameters need an input value and the out parameters don?t.

Variable arguments in C#:

The C# language supports variable arguments through a keyword called params. A typical example for the declaration of a function with variable argument signature is as follows. Public void functionName(int a, params int[] varParam);

Method Overloading in C#:

A method is considered to be an overloaded method, if it has two or more signatures for the same method name. These methods will contain different parameters but the same return types.A simple example for an overloaded methods are:

Public void functionName(int a, params int[] varParam);Public void functionName(int a);

Property in C#:

Property ? it is a special method that can return a current object?s state or set it. Simple syntax of properties can see in the following example:

public int Old{ get {return m_old;} set {m_old = value;}}public string Name{ get {return m_name;}}

Here are two types of properties. A first one can set or get field of class named m_old, and the second is read only. That?s mean it can only get current object?s state.

The significance of these properties is its usability. These properties need not be called with any function names like objectname.get or objectname.set etc., But they can be directly assigned the values or retrieve the values.C# .Net and Java

This article compares the same program written in the C# and Java languages and then compares the dissembled code of both languages.Java Hello Program:

class Hello{public static void main(String args[]){ System.out.println("Hello");}}

Disassembled Java Hello Program:

class Hello{Hello(){ // 0 0:aload_0 // 1 1:invokespecial #1 // 2 4:return}public static void main(String args[]){ System.out.println("Hello"); // 0 0:getstatic #2 // 1 3:ldc1 #3 // 2 5:invokevirtual #4 // 3 8:return}}

Explanation of Java program: To understand this you must have some knowledge of computer internals concepts for eg. Opcodes, instruction templates etc. I assume that you already know them. As usual this code will also start with main method. The first line tells that print ?Hello? it is a normal print statement. A specific instruction, with type information, is built by replacing the ?T? in the instruction template in the opcode column by the letter in the type column. In this case it is a load instruction for type reference. Invokespecial instruction must name an instance initialization method, a method in the current class, or a method in a superclass of the current class. Class and interface initialization methods are invoked implicitly by the Java virtual machine; they are never invoked directly from any Java virtual machine instruction, but are invoked only indirectly as part of the class initialization process.invokevirtual or invokespecial is used to access a protected method of a superclass, then the type of the class instance being accessed must be the same as or a subclass of the current class. The Java virtual machine uses local variables to pass parameters on method invocation. On class method invocation any parameters are passed in consecutive local variables starting from local variable 0.C# Hello Program:

using System;

class Hello{public static void Main(string[] args){ Console.WriteLine("Hello");}}

Disassembled C# Hello Program :

.method private hidebysig static void Main() cil managed{.entrypoint// Code size 11 (0xb).maxstack 8IL_0000: ldstr "Hello"IL_0005: call void [mscorlib]System.Console::WriteLine(class System.String)IL_000a: ret} // end of method Hello::Main

Explanation of C# .Net Program: The first line defines the Main method by using the .method MSIL keyword. Note that the method is defined as being public and static, which are the default modifiers for the Main method. Also note that this method is defined as managed.

The next line of code uses the MSIL .entrypoint keyword to designate this particular method as the entry point to the application. When the .NET runtime executes this application, this is where control will be passed to the program.

Next, look at the MSIL opcodes on lines IL_0000 and IL_0005. The first uses the the ldstr (Load String) opcode to load a hard-coded literal ("Hello") onto the stack.

The next line of code calls the System.Console.WriteLine method. Notice that the MSIL prefixes the method name with the name of the assembly that defines the method. This line also tells us the number of arguments (and their types) that are expected by the method. Here, the method will expect a System.String object to be on the stack when it's called. Finally, line IL_000a is a simple ret MSIL opcode to return from the methodC# .Net Tutorial Attributes

This article deals with the new C# .net features named attributes. This can be used as a Self paced C# .net training or C# tutorial material. C# .net Attributes provide a powerful method of associating declarative information with C# code. It can work with types, methods, properties and other language components. As a thumb-rule, a class is said to be an attribute class, if it directly or indirectly derives from the System.Attribute class.Attributes in C# .net - Sample: This C# tutorial on attributes uses custom attributes by defining an attribute class. The class ProductInfo is derived from System.Attribute class. This class contains information about application author and product version. The created class is:

[AttributeUsage(AttributeTargets.All)]public class ProductInfo : System.Attribute{public ProductInfo(double version,string name){m_version = version;m_authorName = name;}public double Version{get { return m_version; }}private double m_version = 1.00;public string AuthorName{get { return m_authorName; }}private string m_authorName;}

There is a new item in the first line of code. It is an attribute that allows us to use a c# attribute keyword AttributeUsage to all elements of our class (parameter AttributeTargets.All).

Now we can use these c# attributes in declaration of any other custom class:[ProductInfo(1.005,"CoderSource"])public class AnyClass { } After creating simple custom type c# attributes, we can get information about all its attributes at runtime. Such run-time information can be pulled out from a class by using the namespace System.Reflection. In main function of our C# tutorial program we can get from our object all information about custom attributes. Next piece of code demonstrate it:

MemberInfo membInfo;membInfo = typeof(AnyClass);object [] attributes;attributes = membInfo.GetCustomAttributes(typeof(ProductInfo),true);if(attributes.GetLength(0)!=0){ProductInfo pr = (ProductInfo) attributes[0];Console.WriteLine("Product author: {0}",pr.AuthorName);Console.WriteLine("Product version; {0}",pr.Version);}

Using standard methods of getting type information and members of his type we can get all custom attributes.

The example in this C# tutorial uses only one of three library c# attributes (AttributeUsage). It uses only with declaration some custom c# attribute. There is another standard attribute called Conditional. It calls method with that attribute only in case when method application has some needed condition. Most often it is used to define some preprocessor commands (?#?). And the last reserved attribute is Obsolete. It helps us to mark some elements of program that are old to use. These are basic things about attributes and their usage in applications.C# .Net Tutorial Exceptions

This article is a basic c# tutorial dealing with exceptions in c# .net. Practically any program including c# .net can have some amount of errors. They can be broadly classified as compile-time errors and runtime errors. Compile-time errors are errors that can be found during compilation process of source code. Most of them are syntax errors. Runtime errors happen when program is running. It is very difficult to find and debug the run-time errors. These errors also called exceptions. Rules of good coding style say that program must be able to handle any runtime error. Exception generates an exception call at runtime. Exceptions in C# can be called using two methods:1. Using the throw operator. It call the manage code anyway and process an exception.2. If using the operators goes awry, it can generate an exception.Simple Exceptions - .Net C# Tutorial: C# language uses many types of exceptions, which are defined in special classes. All of them are inherited from base class named System.Exception. There are classes that process many kinds of exceptions: out of memory exception, stack overflow exception, null reference exception, index out of range exception, invalid cast exception, arithmetic exception etc. This c# tutorial deals with DivideByZero c# exception and custom classes in c# exceptions. C# has defined some keywords for processing exceptions. The most important are try, catch and finally. The first one to be known is the try operator. This is used in a part of code, where there exists a possibility of exception to be thrown. But operator ?try? is always used with the operators: catch and finally. See the following example of handling a simple exception in c#.

//Sample code for C# Exception tutorial using try , catch// try catch exceptionint zero = 0;try{ int div = 100/zero;}catch(DivideByZeroException){ Console.WriteLine("Division by zero exception passed");}

This code in runtime throws a DivideByZeroException and writes some message through the console. But if you want to release some resources that were created you must use try ? finally construction. Finally will be called even if there were no exceptions raised.

//Sample code for C# Exception tutorial using try, finallyBitmap bit = null;// try finally exceptiontry{ bit = new Bitmap(100,100);}finally{bit.Dispose();Console.WriteLine("bitmap is disposed");}

In the similar way we can use try ? catch ? finally construction. The attached c# tutorial program contains sample including all the three.Custom Exception Classes - C# Tutorial: Some larger projects might have a requirement of creating their own custom exception classes. Let us try to create class that validates email address. It will validate for the ?@? symbol. Please have a look on the following piece of code:

//Sample code for C# .Net Exception tutorial - validates an email addresspublic class TextException : Exception{public TextException() : base()
{}

public TextException(string message) : base(message){

}}

public class MailValidator{MailValidator(){

}

private static char symbol = '@';

public static void TestEnteredMail(string mailAddress){if(mailAddress.IndexOf(symbol)==-1){Console.WriteLine("The string entered is not a valid email address");
throw(new TextException());}}}

Here were created a C# .Net TextException class that inherits from System.Exception class of .NET class library. Actually it does nothing, but there is an additional class MailValidator. It has TestEnteredMail method that raises a TextException. Now look at usage of it in Main function.

try{MailValidator.TestEnteredMail(Console.ReadLine());}catch(TextException){Console.WriteLine("Exception was passed");}

So, if user enters mail address without it throws an exception. All the sources are attached and compliable. The example can be compiled using .NET command line through the csc command line program. You only need to type csc filename.cs. C# .Net Tutorial Interfaces

This C# Tutorial deals with interfaces in C# .Net. An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members.All the member declarations inside interface are implicitly public.

Defining an Interface: Let us look at a simple example for c# interfaces. In this example interface declares base functionality of node object.interface INode{

string Text{get;set;}

object Tag{get;set;}

int Height{get;set;}

int Width{get;set;}

float CalculateArea();

}

The above INode interface has declared a few abstract properties and function which should be implemented by the derived classes.

//Sample for Deriving a class using a C# .Net interface - c# tutorial

public class Node : INode{

public Node(){}public string Text{

get{ return m_text;}

set{ m_text = value;}

}

private string m_text;public object Tag{

get{ return m_tag;}

set{ m_tag = value;}

}

private object m_tag = null;public int Height{

get{ return m_height;}

set{ m_height = value;}

}

private int m_height = 0;public int Width{

get{ return m_width;}

set{ m_width = value;}

}

private int m_width = 0;

public float CalculateArea(){

if((m_width