Pages

Monday, July 22, 2013

Visual CSharp Basics for Beginners

Welcome to DotNet Sql Info.  Visual C# Basics Tutorials for Beginners, C Sharp Basics, C Sharp Tutorials. C# developed by the software giant Microsoft to support Dot Net Framework. C# (C Sharp), a successor to C++, has been released in conjunction with the .NET framework. C# is a completely Object Oriented Programming (OOP) language like Java. If a programmer is familiar with Object Oriented Concepts than C# is not a big deal for programmers to learn C#. Here in this post we are going to provide some basic features and functionality of C#, have a look.

Visual C# Basics Tutorials for Beginners

Visual C# Basics Tutorials for Beginners, C Sharp Basics, C Sharp Tutorials. C# developed by the software giant Microsoft to support Dot Net Framework. C# (C Sharp), a successor to C++, has been released in conjunction with the .NET framework. C# is a completely Object Oriented Programming language like Java. If a programmer is familiar with Object Oriented Concepts than C# is not a big deal for programmers to learn C#. Here in this post we are going to provide some basic features and functionality of C#.


• C# design goals:

– Be comfortable for C++ programmer

– Fit cleanly into the .NET Common Language Runtime (CLR)

– Simplify the C++ model

– Provide the right amount of flexibility

– Support component-centric development

The first component oriented language in the C/C++ family

Everything really is an object

Next generation robust and durable software

Preservation of investment


A component oriented language

C# is the first “component oriented” language in the C/ C++ family

Component concepts are first class:

Properties, methods, events

Design-time and run-time attributes

Integrated documentation using XML

Enables one-stop programming

No header files, IDL, etc.

Can be embedded in web pages

Everything really is an object

Traditional views

C++, Java:  Primitive types are “magic” and do not interoperate with objects

Small talk, Lisp:  Primitive types are objects, but at great performance cost

C# unifies with no performance cost

Deep simplicity throughout system

Improved extensibility and reusability

New primitive types:  Decimal, SQL…

Collections, etc., work for all types

Robust and durable software

Garbage collection

No memory leaks and stray pointers

Exceptions

Error handling is not an afterthought

Type-safety

No uninitialized variables, unsafe casts

Versioning

Pervasive versioning considerations in all aspects of language design

Preservation of Investment

C++ heritage

Namespaces, enums, unsigned types, pointers (in unsafe code), etc.
No unnecessary sacrifices

Interoperability

What software is increasingly about

MS C# implementation talks to XML, SOAP, COM, DLLs, and any .NET language

Millions of lines of C# code in .NET

Short learning curve
Increased productivity

C# Program Structure

Namespaces

Contain types and other namespaces

Type declarations

Classes, structs, interfaces, enums, and delegates

Members

Constants, fields, methods, properties, indexers, events, operators, constructors, destructors

Organization

No header files, code written “in-line”

No declaration order dependence

Type System

• C# is a type-safe language. Variables are declared as being of a particular type, and each variable is constrained to hold only values of its declared type.

• Variables can hold either value types or reference types,or they can be pointers.

• A variable of value types directly contains only an object with the value.

• A variable of reference type directly contains a reference to an object. Another variable many contain a reference to the same object.

• It is possible in C# to define your own value types by declaring enumerations or structs.


Value types

Directly contain data
Cannot be null


Reference types

Contain references to objects
May be null

Example: int i = 123;
string s = "Hello world";


Value types

Primitives int i;
Enums enum State { Off, On }
Structs struct Point { int x, y; }

Reference types

Classes class Foo: Bar, IFoo {...}

Interfaces interface IFoo: IBar {...}

Arrays string[] a = new string[10];

Delegates delegate void Empty();


C# Pre-defined Value Types

C# Type .Net Framework Type Signed Bytes Possible Values

sbyte System.sbyte Yes 1 -128 to 127
short System.Int16 Yes 2 -32768 to 32767
int         System.Int32 Yes 4 231 to 231 - 1
long         System.Int64 Yes 8 263 to 263 - 1
byte         System.Byte No 1 0 to 255
ushort System.Uint16 No 2 0 to 65535
uint         System.Uint32 No 4 0 to 232 - 1
ulong System.Uint64 No 8 0 to 264 - 1
float         System.Single Yes 4 ±1.5 x 10-45 to ±3.4 x 1038 
double System.Double         Yes 8 ±5.0 x 10-324 to ±1.7x 10308
decimal    System.Decimal        Yes 12 ±1.0 x 10-28 to ±7.9 x 1028 
char         System.Char N/A 2 Any Unicode character
bool        System.Boolean         N/A 1/2 true or false


C# predefined types

Reference object, string

Signed sbyte, short, int, long

Unsigned byte, ushort, uint, ulong

Character char

Floating-point float, double, decimal

Logical bool

Predefined types are simply aliases for system-provided types

For example, int == System.Int32


Pointers in C#:

• A pointer is a variable that holds the memory address of another type. In C#, pointers can only be declared to hold the memory addresses of value types.

• Pointers are declared implicitly, using the dereferencer symbol *. The operator & returns the memory address of the variable it prefixes.

• Example: What is the value of i?

int i = 5;
int *p;
p = &i;
*p = 10;

• The use of pointers is restricted to code which is marked as unsafe (memory access).

•To address the problem of garbage collection, one can declare a pointer within a fixed expression.

• Any value types declared within unsafe code are automatically fixed, and will generate compile-time errors if used within fixed expressions. The same is not true for reference types.

• Although pointers usually can only be used with value types, an exception to this involves arrays.

• A pointer can be declared in relation to an array, as in the following:

int[] a = {4, 5};

int *b = a;

What happens in this case is that the memory location held by b is the location of the first type held by a.


Arrays in C#:

Single-dimensional arrays have a single dimension

int[] i = new int[100];

C# supports two types of multidimensional arrays:

rectangular and jagged.
– A rectangular array is a multidimensional array that has the fixed dimensions' sizes.

int[,] squareArray = new int[2,3];
int[,] squareArray = {{1, 2, 3}, {4, 5, 6}};

– A jagged arrays is a multidimensional array that has the irregular dimensions’ sizes.

int[][] jag = new int[2][];
jag[0] = new int [4];
jag[1] = new int [6];
int[][] jag = new int[][] {new int[] {1, 2, 3, 4}, new int[] {5, 6, 7, 8, 9, 10}};

Enumerations in C#: 

• An enumeration is a special kind of value type limited to a restricted and unchangeable set of numerical values.

• When we define an enumeration we provide literals which are then used as constants for their corresponding values. The following code shows an example of such a definition:

public enum DAYS { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
enum byteEnum : byte {A, B};

• Instead, the numerical values are set up according to the following two rules:

– For the first literal: if it is unassigned, set its value to 0.
– For any other literal: if it is unassigned, then set its value to one greater than the value of the preceding literal.


Operators in C#

• C# has a number of standard operators, taken from C, C++ and Java. Most of these should be quite familiar to programmers.

• To overload an operator in a class, one defines a method using the operator keyword. For instance, the following code overloads the equality operator.

public static bool operator == (Value a, Value b) {
return a.Int == b.Int
}

Where an operator is one of a logical pair, both operators should be overwritten if any one is.


Jump and Selection Statements

• The break statement breaks out of the while and for loops.

• The continue statement can be placed in any loop structure.

• The goto statement is used to make a jump to a particular labeled part of the program code.

• If-else statements are used to run blocks of code conditionally upon a boolean expression evaluating to true.

• Switch statements provide a clean way of writing multiple if - else statements.


Loop Statements

• while loops
while (expression) statement[s]

• do-while loops
do statement[s] while (expression)

• for loops
for (statement1; expression; statement2) statement[s]

• foreach loops

foreach (variable1 in variable2) statement[s]
int[] a = new int[]{1,2,3};
foreach (int b in a)
System.Console.WriteLine(b);


Classes and Structs

Classes provide templates from which objects instances of those classes, can be generated. 

A class specifies a type and the constitutive elements (type members) of that type.

A class can specify two main kinds of type member. 

A class can specify other types – both value and reference.Types can contain other types, that is known as containment, or else aggregation.

A class can specify methods – functions designed for reading and manipulating the value and reference types an instance contains.

C# classes can inherit from a single base class or from any number of interfaces.


Classes and it's members in C#:


Classes supports: Single inheritance, Multiple interface implementation


Class members

Constants, fields, methods, properties, indexers, events, operators, constructors, destructors

Static and instance members

Nested types

Member access
public, protected, internal, private


Structs

Like classes, except

Stored in-line, not heap allocated
Assignment copies data, not reference
No inheritance


Ideal for light weight objects

Complex, point, rectangle, color
int, float, double, etc., are all structs


Benefits

No heap allocation, less GC pressure
More efficient use of memory


Example:

class CPoint { int x, y; ... }
struct SPoint { int x, y; ... }

CPoint cp = new CPoint(10, 20);
SPoint sp = new SPoint(10, 20);


Namespaces

• Namespaces can be thought of as collections of classes, they provide unique identifiers for types by placing them in an hierarchical structure.

Class Declaration

• Class declarations can have up to four different parts,

surrounding the class keyword:attributes class-modifiers class class-base class-body

• The class-body element specifies type members. The following is an example of a class declaration:

public class Shape {

    // class-body

}

• Attributes can be posted at the front of a class declaration. 

These comprise user-defined meta-data about the class; information which can be brought out at runtime.

• There are seven different - optional - class modifiers.

Four of these – public, internal, protected, and private

– are used to specify the access levels of the types defined by the classes.

– The public keyword identifies a type as fully accessible to all other types.

– If a class is declared as internal, the type it defines is accessible only to types within the same assembly (a selfcontained 'unit of packaging' containing code, metadata etc.).

– If a class is declared as protected, its type is accessible by a containing type and any type that inherits from this containing type.

– Where a class is declared as private, access to the type it defines is limited to a containing type only.


• The permissions allowed by protected internal are those allowed by the protected level plus those allowed by the internal level.

• The new keyword can be used for nested classes.

• A class declared as abstract cannot itself be instanced it is designed only to be a base class for inheritance.

• A class declared as sealed cannot be inherited from.

• The class base part of the class declaration specifies the name of the class and any classes that it inherits from.

• The following line declares a public class called DrawingRectangle which inherits from the base class Rectangle and the interface Drawing:

public class DrawingRectangle : Rectangle, Drawing

• Interfaces are declared in much the same way as standard classes, except that they use the keyword interface in place of the keyword class. 

For instance: public interface Drawing


Methods

• Methods are operations associated with types.

int sum = Arithmetic.addTwoIntegers(4, 7);

• A method declaration, specified within a class declaration, comprises a method-head and a methodbody.

• The method-head is made up of the following elements (square brackets enclose those which are optional).

[attributes] [method-modifiers] return-type methodname ([ formal-parameter-list] )

• Method attributes work in a similar way to those for classes.

• There are ten method modifiers that can be used. Four of these are the access modifiers that can be used in class declarations. These four work analogously to the way they work in class declarations. 
The others are the following:

Abstract: A method without specifying its body. Such methods are themselves termed abstract. A class contains an abstract method it cannot be instantiated.

– The static modifier declares a method to be a class method (a method that can be invoked without an instance).

• Namespaces (Packages in Java) can be thought of as collections of classes; they provide unique identifiers for types by placing them in an hierarchical structure.


Polymorphism (Inherited Methods)

• C# supports two different ways of method overwriting - hiding or overriding. Note that the term 'overwrite' is a term we have devised to cover both hiding and overriding.

• Method overwriting makes use of the following three method-head keywords:
new, virtual, override

• The main difference between hiding and overriding relates to the choice of which method to call where the declared class of a variable is different to the run-time class of the object it references.


Constants, Fields, Properties and Indexers

• Fields are variables associated with either classes or instances of classes.

• There are seven modifiers which can be used in their declarations. These include the four access modifiers public, protected, internal and private and the new keyword.

• The two remaining modifiers are:

Static: By default, fields are associated with class instances.

Use of the static keyword, however, associates a field with a class itself, so there will only ever be one such field per class, regardless of the number of the class instances.

Readonly: Where a field is read only, its value can be set only once.

• Constants are unchanging types, associated with classes, that are accessible at compile time. Because of this latter fact, constants can only be value types rather than reference types.

public const int area = 4;

• Properties can be thought of as virtual fields. From the outside, a class' property looks just like a field. But from the inside, the property is generated using the actual class fields.

• If properties are virtual fields, indexers are more like virtual arrays. They allow a class to emulate an array, where the elements of this array are actually dynamically generated by function calls.


Enums are Constants : 

Strongly typed

No implicit conversions to/from int
Operators: +, -, ++, --, &, |, ^, ~

Can specify underlying type
Byte, short, int, long
enum Color: byte
{
    Red   = 1,
    Green = 2,
    Blue  = 4,
    Black = 0,
    White = Red | Green | Blue,
}


Delegates and Events

Object oriented function pointers


Multiple receivers

Each delegate has an invocation list
Thread-safe + and - operations


Foundation for events

delegate void MouseEvent(int x, int y);

delegate double Func(double x);

Func func = new Func(Math.Sin);
double x = func(1.0);

• Delegates are reference types which allow indirect calls to methods.

– A delegate instance holds references to some number of methods, and by invoking the delegate one causes all of these methods to be called.

– The usefulness of delegates lies in the fact that the functions which invoke them are blind to the underlying methods.


• It can be seen that delegates are functionally rather similar to C++'s function pointers. However, it important to bear in mind two main differences.

– Firstly, delegates are reference types rather than value types.

– Secondly, some single delegates can reference multiple methods.

• Delegates can be specified on their own in a namespace, or else can be specified within another class. In each case, the declaration specifies a new class, which inherits from System.MulticastDelegate.

• Each delegate is limited to referencing methods of a particular kind only.

– The type is indicated by the delegate declaration – the input parameters and return type given in the delegate declaration must be shared by the methods its delegate instances reference.

• To illustrate this: a delegate specified as below can be used to refer only to methods which have a single String input and no return value.

• public delegate void Print (String s);

• Suppose, for instance, that a class contains the following method:

public void realMethod (String myString) {
// method code
}

• Another method in this class could then instantiate the Print delegate in the following way, so that it holds a reference to realMethod;
Print delegateVariable = new Print(realMethod);

• We can note two important points about this example. Firstly, the unqualified method passed to the delegate constructor is implicitly recognized as a method of the instance passing it. That is, the code is equivalent to:
Print delegateVariable = new Print(this.realMethod);

• We can, however, in the same way pass to the delegate constructor the methods of other class instances, or even static class methods. In the case of the former, the instance must exist at the time the method reference is passed. In the case of the latter (exemplified below), the class need never be instantiated.

Print delegateVariable = new

Print(ExampleClass.exampleMethod);

• The second thing to note about the example is that all delegates can be constructed in this fashion, to create a delegate instance which refers to a single method.

• However, as we noted before, some delegates – termed multicast delegates – can simultaneously reference multiple methods. These delegates must - like our Print delegate – specify a void return type.

• The method invocation is termed an event, and the running of the method is the handling of the event. An typical example of an event is a user's selection of a button on a graphical user interface; this action may trigger a number of methods to handle it.

• The event keyword is used to declare a particular multicast delegate.


Exceptions in C# :

• The exception handling in C#, and Java is quite similar. However, C# follows C++ in allowing the author to ignore more of the exceptions that might be thrown (an exception which is thrown but not caught will halt the program and may throw up a dialogue box).

• To catch a particular type of exception in a piece of code, you have to first wrap it in a try block and then specify a catch block matching that type of exception.

• When an exception occurs in code within the try block, the code execution moves to the end of the try box and looks for an appropriate exception handler.

• For instance, the following piece of code demonstrates catching an exception specifically generated by division by zero:

try {
res = (num / 0);
catch (System.DivideByZeroException e) {
Console.WriteLine("Error: an attempt to divide by zero");
}
}

• You can specify multiple catch blocks (following each other), to catch different types of exception. A program can throw exceptions - including customized exceptions.


Example: 

using System;
public class ExceptionDemo {
public static void Main () {
try {
getException();
catch (Exception e) {
Console.WriteLine("We got an exception");
}}
finally {
Console.WriteLine("The end of the program");
}
}
public static void getException() {
throw new Exception();
}
}



Visual C# Basics Tutorials for Beginners, Basics in  C#, C# Beginners, C Sharp Basics, C Sharp Tutorials.

No comments:

Blogger Tricks And TipsComment here