Você está na página 1de 20

NET - C#.

Net
What is C#?
C# combines the C high productivity of Rapid Application Development (RAD) languages
It will immediately be familiar to C and C++ programmers.
C# combines the C high productivity of Rapid Application Development (RAD) languages.
What are the types of comment in C#?
There are 3 types of comments in C#.
Single line (//)
Multi (/* */)
Page/XML Comments (///)
What are the characteristics of C#?
There are several characteristics of C# are :
Simple
Type safe
Flexible
Object oriented
Compatible
Consistent
Interoperable
What are the different categories of inheritance?
Single inheritance : Contains one base class and one derived class.
Hierarchical inheritance : Contains one base class and multiple derived classes of the same base
class.
Multilevel inheritance : Contains a class derived from a derived class.
Multiple inheritance : Contains several base classes and a derived class.
Hybrid inheritance : is nothing but a any combination of single,multiple and inheritance
inheritance. Multiple inheritance class is not possible as it give assembly level error when we use
the same name for method. Multiple inheritance in interface is possible.



Class

A class is basically a combination of a set of rules on which we will work in a specific program. It
contains definitions of new data types like fields or variables, operations that we will perform on data
(methods) and access rules for that data.

Example
Class Example
{
/* fields,
Variables,
Methods,
Properties,
*/
}

Object

Objects are defined as an instance of a class. Objects are built on the model defined by the class. An
object can be created in memory using the "new" keyword. In C# objects are reference types and other
data type variables are value types. In C# objects are stored in the heap while other value types are stored
in the stack.

Example

Example exmplObject = new Example();

Inheritance

Inheritance is relevant due to the concept of Code Reusability. Inheritance is a feature by which a class
acquires attributes of another class. The class that provides its attributes is known as the base class and the
class that accepts those attributes is known as a derived class. It allows programmers to enhance their
class without reconstructing it.

Example

class BaseClass
{
}
class DerivedClass : BaseClass
{
}

Now an object of a derived class can use the accessible properties of the base class without defining it in
the derived class.

Encapsulation

Encapsulation is defined as hiding irrelevant data from the user. A class may contain much information
that is not useful for an outside class or interface. The idea behind this concept is Dont tell me how you
do it. Just do it..

So classes use encapsulation to hide its members that are not relevant for an outside class or interface.
Encapsulation can be done using access specifiers.

Abstraction

Abstraction is defined as showing only the relevant data to the user. Generally abstraction and
encapsulation are explained in confusing manners.

Example

So just take an example of Mobile Phone Design.
Relevant Features of a phone in which the user is interested are Camera, Music player, Calling
function, Voice recording and so on.
Irrelevant Features of a phone in which the user is not interested are circuit board design, hardware used
and so on.

So in designing the Mobile Phone Model, both relevant and irrelevant features are required. But we need
to show only relevant features. So we design a Mobile Phone in such a way that only relevant features are
shown and irrelevant features are hidden. And remember one thing, that deciding relevant and irrelevant
features is totally a user choice.

Polymorphism

Polymorphism is defined as the implementation of the same method with different attributes in a different
context.

Example

For example, we have a class named shape with a method name buildshape(). We need to use it in the
class Circle, class triangle and the class quadrilateral. So for every class we use the buildshape() method
but with different attributes.
About Abstract Class
Abstract class in csharp is defined using "abstract" keyword
An abstract class may contain abstract methods and accessors (properties).
Non abstract methods or properties should provide actual implementation in an abstract class.
Abstract classes that cannot be instantiated mean we cannot able to create an object of an abstract
class but abstract class can be implemented to child classes like a common base class. An abstract class
can be partially implemented or not at all implemented.
Syntax

abstract class absCalculator
...code starts here
}
In an abstract class a method which has a keyword "abstract" and doesn't provide any implementation is
called abstract method.The implementation logic of abstract methods is provided by the child classes or
derived classes.Child classes use keyword "override" with same method name (as abstract method name)
to provide further implementation of abstract methods.
Non Abstract Method
In an abstract class a method which doesn't have a keyword "abstract" and provide any implementation is
called non abstract method.
Why Abstract Class
Abstract class enforces derived classes to provide all implementation logic for abstract methods or
properties.
Use of an Abstract Class
Use abstract class when you want to create a common base class for a family of types and with some
implementation
Subclass only a base class in a hierarchy to which the class logically belongs.
Below a simple example in c# which illustrates abstract class with abstract methods and non abstract
methods.
First step lets create an abstract class "absCalculate" having abstract methods and non abstract methods.

abstract class absCalculate

//A Non abstract method
public int Addition(int Num1, int Num2)

return Num1 + Num2;
}

//An abstract method, to be overridden in derived class
public abstract int Multiplication(int Num1, int Num2);
}

Now next step lets create a class "clsCalculate" and implement it with abstract class "absCalculate".
class clsCalculate:absCalculate

...code
}
And now lets build this application.
And now lets build this application.


When we build this application we got the following error because we have not provided implementation
of an abstract method as you can see it in above snapshot.
Now lets give implementation for an abstract method using override keyword implementing the abstract
method as you can see in our below code.

class clsCalculate:absCalculate


//using override keyword implementing the abstract method
public override int Multiplication(int Num1, int Num2)

return Num1 * Num2;
}
}
Finally lets create an object of class "clsCalculate" in our main program of an console application and see
the output.

class Program


static void Main(string[] args)


Console.WriteLine("Please Enter First Number");
int num1 = Convert.ToInt16(Console.ReadLine());

Console.WriteLine("Please Enter Second Number");
int num2 = Convert.ToInt16(Console.ReadLine());

absCalculate objabCal = new clsCalculate();
int add = objabCal.Addition(num1, num2);
int multiplied = objabCal.Multiplication(num1, num2);
Console.WriteLine("Added Number is : 0}, Multiplied Number is : 1}", add, multiplied);
}
}

Output


ENCAPSULATION



public class Account
{
private string accoutName="SAVING_ACCOUNT";
// property which has get and set
public string AccoutName
{
get
{
return accoutName;
}
set
{
accoutName = value;
}
}
private string address="India";
// readonly property
public string Address
{
get
{
return address;
}
}
private string phone = "1234567890";
// writeonly property
public string Phone
{
set
{
phone=value;
}
}
}

static void Main()
{
// Encapsulation using properties
string name = string.Empty;
Account account = new Account();
// call get part
name = account.AccoutName;
// change the value
name = "CURRENT_ACCOUNT";
// call set part
account.AccoutName = name;
string address = string.Empty;
// call readonly property
address = account.Address;
// now address has value India
string phone = "1234567890";
// call writeonly property
account.Phone = phone;
// now account.Phone has value 1234567890
}
Modern, general-purpose programming language
Object oriented.
Component oriented.
Easy to learn.
Structured language.
It produces efficient programs.
It can be compiled on a variety of computer platforms.
Part of .Net Framework.
Features of C#
Boolean Conditions
Automatic Garbage Collection
Standard Library
Assembly Versioning
Properties and Events
Delegates and Events Management
Easy-to-use Generics
Indexers
Conditional Compilation
Simple Multithreading
LINQ and Lambda Expressions
Integration with Windows







A class is a construct that enables you to create your own custom types by grouping together variables of
other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If
the class is not declared as static, client code can use it by creating objects or instances which are assigned
to a variable. The variable remains in memory until all references to it go out of scope. At that time, the
CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in
memory and client code can only access it through the class itself, not an instance variable. For more
information, see Static Classes and Static Class Members (C# Programming Guide).
Creating Objects
Although they are sometimes used interchangeably, a class and an object are different things. A class
defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is
sometimes referred to as an instance of a class.
Objects can be created by using the new keyword followed by the name of the class that the object will
be based on, like this:
C#
Customer object1 = new Customer();
When an instance of a class is created, a reference to the object is passed back to the programmer. In the
previous example, object1 is a reference to an object that is based on Customer. This reference refers to
the new object but does not contain the object data itself. In fact, you can create an object reference
without creating an object at all:
C#
Customer object2;
We do not recommend creating object references such as this one that does not refer to an object
because trying to access an object through such a reference will fail at run time. However, such a
reference can be made to refer to an object, either by creating a new object, or by assigning it to an
existing object, such as this:
C#
Customer object3 = new Customer();
Customer object4 = object3;
This code creates two object references that both refer to the same object. Therefore, any changes to the
object made through object3 will be reflected in subsequent uses of object4. Because objects that are
based on classes are referred to by reference, classes are known as reference types.
Class Inheritance
Inheritance is accomplished by using a derivation, which means a class is declared by using a base
class from which it inherits data and behavior. A base class is specified by appending a colon and the
name of the base class following the derived class name, like this:
C#
public class Manager : Employee
{
// Employee fields, properties, methods and events are inherited
// New Manager fields, properties, methods and events go here...
}
When a class declares a base class, it inherits all the members of the base class except the constructors.
Unlike C++, a class in C# can only directly inherit from one base class. However, because a base class may
itself inherit from another class, a class may indirectly inherit multiple base classes. Furthermore, a class
can directly implement more than one interface. For more information, see Interfaces (C# Programming
Guide).
A class can be declared abstract. An abstract class contains abstract methods that have a signature
definition but no implementation. Abstract classes cannot be instantiated. They can only be used through
derived classes that implement the abstract methods. By constrast, a sealed class does not allow other
classes to derive from it. For more information, see Abstract and Sealed Classes and Class Members (C#
Programming Guide).
Class definitions can be split between different source files. For more information, see Partial Classes and
Methods (C# Programming Guide).
Description
In the following example, a public class that contains a single field, a method, and a special method called
a constructor is defined. For more information, see Constructors (C# Programming Guide). The class is
then instantiated with the new keyword.
Example
C#
public class Person
{
// Field
public string name;

// Constructor that takes no arguments.
public Person()
{
name = "unknown";
}

// Constructor that takes one argument.
public Person(string nm)
{
name = nm;
}

// Method
public void SetName(string newName)
{
name = newName;
}
}
class TestPerson
{
static void Main()
{
// Call the constructor that has no parameters.
Person person1 = new Person();
Console.WriteLine(person1.name);

person1.SetName("John Smith");
Console.WriteLine(person1.name);

// Call the constructor that has one parameter.
Person person2 = new Person("Sarah Jones");
Console.WriteLine(person2.name);

// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output:
// unknown
// John Smith
// Sarah Jones
<access specifier> class class_name
{
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
<access specifier> <return type> method2(parameter_list)
{
// method body
}
...
<access specifier> <return type> methodN(parameter_list)
{
// method body
}
}
using System;

C# BASIC SYNTAX
namespace RectangleApplication
{
class Rectangle
{
// member variables
double length;
double width;
public void Acceptdetails()
{
length = 4.5;
width = 3.5;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}

class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 3.5
Area: 15.75

CONSTRUCTOR
Constructors can be divided into 5 types:
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor
Default Constructor

A constructor without any parameters is called a default constructor; in other words this type of
constructor does not take parameters. The drawback of a default constructor is that every instance of the
class will be initialized to the same values and it is not possible to initialize each instance of the class to
different values. The default constructor initializes:
1. All numeric fields in the class to zero.
2. All string and object fields to null.
Example
using System;
namespace DefaultConstractor
{
class addition
{
int a, b;
public addition() //default contructor
{
a = 100;
b = 175;
}

public static void Main()
{
addition obj = new addition(); //an object is created , constructor is called
Console.WriteLine(obj.a);
Console.WriteLine(obj.b);
Console.Read();
}
}
}
Now run the application, the output will be as in the following:

Parameterized Constructor

A constructor with at least one parameter is called a parametrized constructor. The advantage of
a parametrizedconstructor is that you can initialize each instance of the class to different values.

using System;
namespace Constructor
{
class paraconstrctor
{
public int a, b;
public paraconstrctor(int x, int y) // decalaring Paremetrized Constructor with passing x,y parameter
{
a = x;
b = y;
}
}
class MainClass
{
static void Main()
{
paraconstrctor v = new paraconstrctor(100, 175); // Creating object of Parameterized
Constructor and passing values
Console.WriteLine("-----------parameterized constructor example by vithal wadje---------------");
Console.WriteLine("\t");
Console.WriteLine("value of a=" + v.a );
Console.WriteLine("value of b=" + v.b);
Console.Read();
}
}
}
Now run the application, the output will be as in the following:

Copy Constructor

The constructor which creates an object by copying variables from another object is called a copy
constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing
instance.

Syntax

public employee(employee emp)
{
name=emp.name;
age=emp.age;
}

The copy constructor is invoked by instantiating an object of type employee and passing it the object to
be copied.

Example
employee emp1=new employee (emp2);
Now, emp1 is a copy of emp2.

So let us see its practical implementation.
using System;
namespace copyConstractor
{
class employee
{
private string name;
private int age;
public employee(employee emp) // declaring Copy constructor.
{
name = emp.name;
age = emp.age;
}
public employee(string name, int age) // Instance constructor.
{
this.name = name;
this.age = age;
}
public string Details // Get deatils of employee
{
get
{
return " The age of " + name +" is "+ age.ToString();
}
}
}
class empdetail
{
static void Main()
{
employee emp1 = new employee("Vithal", 23); // Create a new employee object.
employee emp2 = new employee(emp1); // here is emp1 details is copied to emp2.
Console.WriteLine(emp2.Details);
Console.ReadLine();
}
}
}
Now run the program, the output will be as follows:


Static Constructor

When a constructor is created as static, it will be invoked only once for all of instances of the class and it is
invoked during the creation of the first instance of the class or the first reference to a static member in the
class. A static constructor is used to initialize static fields of the class and to write the code that needs to
be executed only once.

Some key points of a static constructor is:
1. A static constructor does not take access modifiers or have parameters.
2. A static constructor is called automatically to initialize the class before the first instance is created
or any static members are referenced.
3. A static constructor cannot be called directly.
4. The user has no control on when the static constructor is executed in the program.
5. A typical use of static constructors is when the class is using a log file and the constructor is used
to write entries to this file.
Syntax

class employee
{// Static constructor
static employee(){}
}
Now let us see it with practically
using System;
namespace staticConstractor
{
public class employee
{
static employee() // Static constructor declaration{Console.WriteLine("The static constructor ");
}
public static void Salary()
{
Console.WriteLine();
Console.WriteLine("The Salary method");
}
}
class details
{
static void Main()
{
Console.WriteLine("----------Static constrctor example by vithal wadje------------------");
Console.WriteLine();
employee.Salary();
Console.ReadLine();
}
}
}
Now run the program the output will be look as in the following:

Private Constructor
When a constructor is created with a private specifier, it is not possible for other classes to derive from
this class,
neither is it possible to create an instance of this class. They are usually used in classes
that contain static members
only. Some key points of a private constructor are:
1. One use of a private constructor is when we have only static members.
2. It provides an implementation of a singleton class pattern
3. Once we provide a constructor that is either private or public or any, the compiler will not add
theparameter-less public constructor to the class.
Now let us see it practically.
using System;
namespace defaultConstractor
{
public class Counter
{
private Counter() //private constrctor declaration
{
}
public static int currentview;
public static int visitedCount()
{
return ++ currentview;
}
}
class viewCountedetails
{
static void Main()
{
// Counter aCounter = new Counter(); // Error
Console.WriteLine("-------Private constructor example by vithal wadje----------");
Console.WriteLine();
Counter.currentview = 500;
Counter.visitedCount();
Console.WriteLine("Now the view count is: {0}", Counter.currentview);
Console.ReadLine();
}
}
}
Now run the application; the output is:

Você também pode gostar