If you want to learn Csharp Programming, Then follow my blog until you become a programmer
Don't wanna be here? Send us removal request.
Text
C# DataTypes
Data Types in a programming language describes that what type of data a variable can hold . CSharp is a strongly typed language, therefore every variable and object must have a declared type. The CSharp type system contains three Type categories. They areValue Types , Reference Types and Pointer Types . In CSharp it is possible to convert a value of one type into a value of another type . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called unboxing .
When we declare a variable, we have to tell the compiler about what type of the data the variable can hold or which data type the variable belongs to.
Syntax : DataType VariableName DataType : The type of data that the variable can hold VariableName : the variable we declare for hold the values.
Example:
int count; int : is the data type count : is the variable name
The above example shows , declare a variable 'count' for holding an integer values.
The following are the commonly using datatypes in C# .
bool
The bool keyword is an alias of System.Boolean. It is used to declare variables to store the Boolean values, true and false. In C# , there is no conversion between the bool type and other types.
C# Runtime type : System.Boolean CSharp declaration : bool flag; CSharp Initialization : flag = true; CSharp default initialization value : false
int
int variables are stored signed 32 bit integer values in the range of -2,147,483,648 to +2,147,483,647
C# Runtime type : System.Int32 CSharp declaration : int count; CSharp Initialization : count = 100; CSharp default initialization value : 0
decimal
The decimal keyword denotes a 128-bit data type.The approximate range and precision for the decimal type are -1.0 X 10-28 to 7.9 X 1028
C# Runtime type : System.Decimal CSharp declaration : decimal val; CSharp Initialization : val = 0.12; CSharp default initialization value : 0.0M
string
The string type represents a string of Unicode characters. string variables are stored any number of alphabetic,
numerical, and special characters .
C# Runtime type : System.String CSharp declaration : string str; CSharp Initialization : str = "csharp string";
0 notes
Text
C# boxing and unboxing
C# Type System contains three Types , they are Value Types , Reference Types and Pointer Types. C# allows us to convert a Value Type to a Reference Type, and back again to Value Types . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing.
Boxing
1: int Val = 1; 2: Object Obj = Val; //Boxing
The first line we created a Value Type Val and assigned a value to Val. The second line , we created an instance of Object Obj and assign the value of Val to Obj. From the above operation (Object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding Reference Type . These types of operation is called Boxing.
UnBoxing
1: int Val = 1; 2: Object Obj = Val; //Boxing 3: int i = (int)Obj; //Unboxing
The first two line shows how to Box a Value Type . The next line (int i = (int) Obj) shows extracts the Value Type from the Object . That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.
Boxing and UnBoxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed , also the cast required for UnBoxing is also expensive computationally.
0 notes
Text
C# Types
A Type is characterized as an arrangement of information and the operations performed on them. CSharp is a specifically dialect. The CSharp sort framework contains three Type classes. They are Value Types , Reference Types and Pointer Types . The Value Types store the information while the Reference Types store references to the real information. Pointer Types variable utilize just in dangerous mode. The Value Types got from System.ValueType and the Reference Types got from System.Object .

The primary distinction between Value Types and Reference Types is that how these Types store the qualities in memory. Regular Language Runtime (CLR) assigns memory in Stack and the Heap . A Value Type holds its genuine incentive in memory assigned on the Stack and Reference Types alluded to as items, store references to the real information. In C# it is conceivable to change over an estimation of one write into an estimation of another sort . The operation of Converting a Value Type to a Reference Type is called Boxing and the switch operation is called Unboxing.
0 notes
Text
C# Interfaces
In previous chapters, we had a look at abstract classes. Interfaces are much like abstract classes and they share the fact that no instances of them can be created. However, interfaces are even more conceptual than abstract classes, since no method bodies are allowed at all. So an interface is kind of like an abstract class with nothing but abstract methods, and since there are no methods with actual code, there is no need for any fields. Properties are allowed though, as well as indexers and events. You can consider an interface as a contract - a class that implements it is required to implement all of the methods and properties. However, the most important difference is that while C# doesn't allow multiple inheritance, where classes inherit more than a single base class, it does in fact allow for implementation of multiple interfaces!
So, how does all of this look in code? Here's a pretty complete example. Have a look, perhaps try it out on your own, and then read on for the full explanation:
using System; using System.Collections.Generic; namespace Interfaces { class Program { static void Main(string[] args) { List<Dog> dogs = new List<Dog>(); dogs.Add(new Dog("Fido")); dogs.Add(new Dog("Bob")); dogs.Add(new Dog("Adam")); dogs.Sort(); foreach(Dog dog in dogs) Console.WriteLine(dog.Describe()); Console.ReadKey(); } } interface IAnimal { string Describe(); string Name { get; set; } } class Dog : IAnimal, IComparable { private string name; public Dog(string name) { this.Name = name; } public string Describe() { return "Hello, I'm a dog and my name is " + this.Name; } public int CompareTo(object obj) { if(obj is IAnimal) return this.Name.CompareTo((obj as IAnimal).Name); return 0; } public string Name { get { return name; } set { name = value; } } } }
Let's start in the middle, where we declare the interface. As you can see, the only difference from a class declaration, is the keyword used - interface instead of class. Also, the name of the interface is prefixed with an I for Interface - this is simply a coding standard, and not a requirement. You can call your interfaces whatever you want, but since they are used like classes so much that you might have a hard time telling the difference in some parts of your code, the I prefix makes pretty good sense. Read: C Sharp
Then we declare the Describe method, and afterwards, the Name property, which has both a get and a set keyword, making this a read and writeable property. You will also notice the lack of access modifiers (public, private, protected etc.), and that's because they are not allowed in an interface - they are all public by default.
Next up is our Dog class. Notice how it looks just like inheriting from another class, with the colon between the class name and the class/interface being subclassed/implemented. However, in this case, two interfaces are implemented for the same class, simply separated by a comma. You can implement as many interfaces as you want to, but in this case we only implement two - our own IAnimal interface, and the .NET IComparable interface, which is a shared interface for classes that can be sorted. Now as you can see, we have implemented both the method and the property from the IAnimal interface, as well as a CompareTo method from the IComparable interface.
Now you might be thinking: If we have to do all the work our self, by implementing the entire methods and properties, why even bother? And a very good example of why it's worth your time, is given in the top of our example. Here, we add a bunch of Dog objects to a list, and then we sort the list. And how does the list know how to sort dogs? Because our Dog class has a CompareTo method that can tell how to compare two dogs. And how does the list know that our Dog object can do just that, and which method to call to get the dogs compared? Because we told it so, by implementing an interface that promises a CompareTo method! This is the real beauty of interfaces.
0 notes
Text
C# More abstract classes
In the previous chapter, we had a look at abstract classes. In this chapter, we will expand the examples a bit, and throw in some abstract methods as well. Abstract methods are only allowed within abstract classes. Their definition will look like a regular method, but they have no code inside them:
abstract class FourLeggedAnimal { public abstract string Describe(); }
So, why would you want to define an empty method that does nothing? Because an abstract method is an obligation to implent that very method in all subclasses. In fact, it's checked at compile time, to ensure that your subclasses has this method defined. Once again, this is a great way to create a base class for something, while still maintaining a certain amount of control of what the subclasses should be able to do. With this in mind, you can always treat a subclass as its baseclass, whenever you need to use methods defined as abstract methods on the baseclass. For instance, consider the following example: Read: C Sharp
namespace AbstractClasses { class Program { static void Main(string[] args) { System.Collections.ArrayList animalList = new System.Collections.ArrayList(); animalList.Add(new Dog()); animalList.Add(new Cat()); foreach(FourLeggedAnimal animal in animalList) Console.WriteLine(animal.Describe()); Console.ReadKey(); } } abstract class FourLeggedAnimal { public abstract string Describe(); } class Dog : FourLeggedAnimal { public override string Describe() { return "I'm a dog!"; } } class Cat : FourLeggedAnimal { public override string Describe() { return "I'm a cat!"; } } }
As you can see, we create an ArrayList to contain our animals. We then instantiate a new dog and a new cat and add them to the list. They are instantiated as a Dog and a Cat respectively, but they are also of the type FourLeggedAnimal, and since the compiler knows that subclasses of that class contains the Describe() method, you are actually allowed to call that method, without knowing the exact type of animal. So by typecasting to the FourLeggedAnimal, which is what we do in the foreach loop, we get access to members of the subclasses. This can be very useful in lots of scenarios.
0 notes
Text
C# Abstract classes
Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error. Instead, you have to subclass them, as taught in the chapter on inheritance, and create an instance of your subclass. So when do you need an abstract class? It really depends on what you do.
To be honest, you can go a long way without needing an abstract class, but they are great for specific things, like frameworks, which is why you will find quite a bit of abstract classes within the .NET framework it self. A good rule of thumb is that the name actually makes really good sense - abstract classes are very often, if not always, used to describe something abstract, something that is more of a concept than a real thing. Read: C Sharp
In this example, we will create a base class for four legged animals and then create a Dog class, which inherits from it, like this:
namespace AbstractClasses { class Program { static void Main(string[] args) { Dog dog = new Dog(); Console.WriteLine(dog.Describe()); Console.ReadKey(); } } abstract class FourLeggedAnimal { public virtual string Describe() { return "Not much is known about this four legged animal!"; } } class Dog : FourLeggedAnimal { } }
If you compare it with the examples in the chapter about inheritance, you won't see a big difference. In fact, the abstract keyword in front of the FourLeggedAnimal definition is the biggest difference. As you can see, we create a new instance of the Dog class and then call the inherited Describe() method from the FourLeggedAnimal class. Now try creating an instance of the FourLeggedAnimal class instead:
FourLeggedAnimal someAnimal = new FourLeggedAnimal();
You will get this fine compiler error:
Cannot create an instance of the abstract class or interface 'AbstractClasses.FourLeggedAnimal'
Now, as you can see, we just inherited the Describe() method, but it isn't very useful in it's current form, for our Dog class. Let's override it:
class Dog : FourLeggedAnimal { public override string Describe() { return "This four legged animal is a Dog!"; } }
In this case, we do a complete override, but in some cases, you might want to use the behavior from the base class in addition to new functionality. This can be done by using the base keyword, which refers to the class we inherit from:
abstract class FourLeggedAnimal { public virtual string Describe() { return "This animal has four legs."; } } class Dog : FourLeggedAnimal { public override string Describe() { string result = base.Describe(); result += " In fact, it's a dog!"; return result; } }
Now obviously, you can create other subclasses of the FourLeggedAnimal class - perhaps a cat or a lion? In the next chapter, we will do a more advanced example and introduce abstract methods as well. Read on.
0 notes
Text
C# Inheritance
One of the absolute key aspects of Object Oriented Programming (OOP), which is the concept that C# is built upon, is inheritance, the ability to create classes which inherits certain aspects from parent classes. The entire .NET framework is built on this concept, with the "everything is an object" as a result of it. Even a simple number is an instance of a class, which inherits from the System.Object class, although .NET helps you out a bit, so you can assign a number directly, instead of having to create a new instance of e.g. the integer class.
This subject can be a bit difficult to comprehend, but sometimes it help with some examples, so let's start with a simple one of those:
public class Animal { public void Greet() { Console.WriteLine("Hello, I'm some sort of animal!"); } } public class Dog : Animal { }
First, we define an Animal class, with a simple method to output a greeting. Then we define a Dog class, and with a colon, we tell C# that the Dog class should inherit from the Animal class. The beautiful thing about this is that it makes sense in the real world as well - a Dog is, obviously, an Animal. Let's try using the classes:
Animal animal = new Animal(); animal.Greet(); Dog dog = new Dog(); dog.Greet();
If you run this example, you will notice that even though we have not defined a Greet() method for the Dog class, it still knows how to greet us, because it inherits this method from the Animal class. However, this greeting is a bit anonymous, so let's customize it when we know which animal it is:
public class Animal { public virtual void Greet() { Console.WriteLine("Hello, I'm some sort of animal!"); } } public class Dog : Animal { public override void Greet() { Console.WriteLine("Hello, I'm a dog!"); } }
Besides the added method on the Dog class, you should notice two things: I have added the virtual keyword to the method on the Animal class, and on the Dog class, I use the override keyword. Read: C Sharp
In C#, you are not allowed to override a member of a class unless it's marked as virtual. If you want to, you can still access the inherited method, even when you override it, using the base keyword.
public override void Greet() { base.Greet(); Console.WriteLine("Yes I am - a dog!"); }
Methods is not the only thing to get inherited, though. In fact, pretty much all class members will be inherited, including fields and properties. Just remember the rules of visibilty, as discussed in a previous chapter.
Inheritance is not only from one class to another - you can have a whole hierarchy of classes, which inherits from eachother. For instance, we could create a Puppy class, which inherits from our Dog class, which in turn inherits from the Animal class. What you can't do in C#, is to let one class inherit from several other classes at the same time. Multiple inheritance, as it's called, is not supported by C#.
0 notes
Text
C# Static members
As we saw in a previous chapter, the usual way to communicate with a class, is to create a new instance of the class, and then work on the resulting object. In most cases, this is what classes are all about - the ability to instantiate multiple copies of the same class and then use them differently in some way. However, in some cases, you might like to have a class which you may use without instantiating it, or at least a class where you can use members of it without creating an object for it. For instance, you may have a class with a variable that always remains the same, no matter where and how it's used. This is called a static member, static because it remains the same.
A class can be static, and it can have static members, both functions and fields. A static class can't be instantiated, so in other words, it will work more as a grouping of related members than an actual class. You may choose to create a non-static class instead, but let it have certain static members. A non-static class can still be instantiated and used like a regular class, but you can't use a static member on an object of the class. A static class may only contain static members.
First, here is an example of a static class:
public static class Rectangle { public static int CalculateArea(int width, int height) { return width * height; } }
As you can see, we use the static keyword to mark the class as static, and then we use it again to mark the method, CalculateArea, as static as well. If we didn't do that, the compiler would complain, since we can't have a non-static member of a static class.
To use this method, we call it directly on the class, like this:
Console.WriteLine("The area is: " + Rectangle.CalculateArea(5, 4));
We could add other helpful methods to the Rectangle class, but perhaps you are wondering why we are passing on width and height to the actual method, instead of storing it inside the class and then pulling them from there when needed? Because it's static! We could store them, but only one set of dimensions, because there is only one version of a static class. This is very important to understand. Read: C Sharp
Instead, we can make the class non-static, and then have the CalculateArea as a utility function on this class:
public class Rectangle { private int width, height; public Rectangle(int width, int height) { this.width = width; this.height = height; } public void OutputArea() { Console.WriteLine("Area output: " + Rectangle.CalculateArea(this.width, this.height)); } public static int CalculateArea(int width, int height) { return width * height; } }
As you can see, we have made the class non-static. We have also added a constructor, which takes a width and a height and assigns it to the instance. Then we have added an OutputArea method, which uses the static method to calculate the area. This is a fine example of mixing static members with non-static members, in a non-static class.
A common usage of static classes, although frowned upon by some people, are utility/helper classes, where you collect a bunch of useful methods, which might not belong together, but doesn't really seem to fit elsewhere either.
0 notes
Text
C# Visibility
The visibility of a class, a method, a variable or a property tells us how this item can be accessed. The most common types of visibility are private and public, but there are actually several other types of visibility within C#. Here is a complete list, and although some of them might not feel that relevant to you right now, you can always come back to this page and read up on them: public - the member can be reached from anywhere. This is the least restrictive visibility. Enums and interfaces are, by default, publicly visible. protected - members can only be reached from within the same class, or from a class which inherits from this class. Read: C Sharp internal - members can be reached from within the same project only. protected internal - the same as internal, except that also classes which inherits from this class can reach it members, even from another project. private - can only be reached by members from the same class. This is the most restrictive visibility. Classes and structs are by default set to private visibility. So for instance, if you have two classes, Class1 and Class2, private members from Class1 can only be used within Class1. You can't create a new instance of Class1 inside of Class2, and then expect to be able to use its private members. If Class2 inherits from Class1, then only non-private members can be reached from inside of Class2.
0 notes
Text
C# Method overloading
A lot of programming languages supports a technique called default/optional parameters. It allows the programmer to make one or several parameters optional, by giving them a default value. It's especially practical when adding functionality to existing code.
For instance, you may wish to add functionality to an existing function, which requires one or more parameters to be added. By doing so, you would break existing code calling this function, since they would now not be passing the required amount of parameters. To work around this, you could define the newly added parameters as optional, and give them a default value that corresponds to how the code would work before adding the parameters.
Default parameters were introduced in C# version 4.0, but up until that, C# coders have been using a different technique, which basically does the same, called method overloading. It allows the programmer do define several methods with the same name, as long as they take a different set of parameters. When you use the classes of the .NET framework, you will soon realize that method overloading is used all over the place. A good example of this, is the Substring() method of the String class. It is with an extra overload, like this:
string Substring (int startIndex) string Substring (int startIndex, int length)
You can call it with either one or two parameters. If you only call it with one parameter, the length parameter is assumed to be the rest of the string, saving us time whenever we simply want to get the last part of a string.
So, by defining several versions of the same function, how do we avoid having the same code several places? It's actually quite simple: We let the simple versions of the method make the complex version of it do all the work. Consider the following example:
class SillyMath { public static int Plus(int number1, int number2) { return Plus(number1, number2, 0); } public static int Plus(int number1, int number2, int number3) { return number1 + number2 + number3; } }
We define a Plus method, in two different versions. The first one takes two paramaters, for adding two numbers, while the second version takes three numbers. The actual work is done in the version that takes three numbers - if we only wish to add two, we call the three parameter version, and simply use 0 as the third paramater, acting as a default value. I know, I know, it's a silly example, as indicated by the name of the class, but it should give you an idea about how it all works. Read: C Sharp
Now, whenever you feel like doing advanced math by adding a total of four numbers (just kidding here), it's very simple to add a new overload:
class SillyMath { public static int Plus(int number1, int number2) { return Plus(number1, number2, 0); } public static int Plus(int number1, int number2, int number3) { return Plus(number1, number2, number3, 0); } public static int Plus(int number1, int number2, int number3, int number4) { return number1 + number2 + number3 + number4; } }
The cool thing about this, is that all your existing calls to the Plus method will continue working, as if nothing had been changed. The more you use C#, the more you will learn to appreciate method overloading.
0 notes
Text
C# Constructors and destructors
Constructors are special methods, used when instantiating a class. A constructor can never return anything, which is why you don't have to define a return type for it. A normal method is defined like this:
public string Describe()
A constructor can be defined like this:
public Car()
In our example for this chapter, we have a Car class, with a constructor which takes a string as argument. Of course, a constructor can be overloaded as well, meaning we can have several constructors, with the same name, but different parameters. Here is an example:
public Car() { } public Car(string color) { this.color = color; }
A constructor can call another constructor, which can come in handy in several situations. Here is an example:
public Car() { Console.WriteLine("Constructor with no parameters called!"); } public Car(string color) : this() { this.color = color; Console.WriteLine("Constructor with color parameter called!"); }
If you run this code, you will see that the constructor with no parameters is called first. This can be used for instantiating various objects for the class in the default constructor, which can be called from other constructors from the class. If the constructor you wish to call takes parameters, you can do that as well. Here is a simple example:
public Car(string color) : this() { this.color = color; Console.WriteLine("Constructor with color parameter called!"); } public Car(string param1, string param2) : this(param1) { }
If you call the constructor which takes 2 parameters, the first parameter will be used to invoke the constructor that takes 1 parameter. Read: C Sharp
Destructors
Since C# is garbage collected, meaing that the framework will free the objects that you no longer use, there may be times where you need to do some manual cleanup. A destructor, a method called once an object is disposed, can be used to cleanup resources used by the object. Destructors doesn't look very much like other methods in C#. Here is an example of a destructor for our Car class:
~Car() { Console.WriteLine("Out.."); }
Once the object is collected by the garbage collector, this method is called.
0 notes
Text
C# classes Properties
Properties allow you to control the accessibility of a classes variables, and is the recommended way to access variables from the outside in an object oriented programming language like C#. In our chapter on classes, we saw the use of a property for the first time, and the concept is actually quite simple. A property is much like a combination of a variable and a method - it can't take any parameters, but you are able to process the value before it's assigned to our returned. A property consists of 2 parts, a get and a set method, wrapped inside the property:
private string color; public string Color { get { return color; } set { color = value; } }
The get method should return the variable, while the set method should assign a value to it. Our example is as simple as it gets, but it can be extended. Another thing you should know about properties is the fact that only one method is required - either get or set, the other is optional. This allows you to define read-only and write-only properties. Here is a better example of why properties are useful:
public string Color { get { return color.ToUpper(); } set { if(value == "Red") color = value; else Console.WriteLine("This car can only be red!"); } }
Okay, we have just made our property a bit more advanced. The color variable will now be returned in uppercase characters, since we apply the ToUpper() method to it before returning it, and when we try to set the color, only the value "Red" will be accepted. Sure, this example is not terrible useful, but it shows the potential of properties. Read: C Sharp
0 notes
Text
Introduction to C# classes
In lots of programming tutorials, information about classes will be saved for much later. However, since C# is all about Object Oriented programming and thereby classes, we will make a basic introduction to the most important stuff already now.
First of all, a class is a group of related methods and variables. A class describes these things, and in most cases, you create an instance of this class, now referred to as an object. On this object, you use the defined methods and variables. Of course, you can create as many instances of your class as you want to. Classes, and Object Oriented programming in general, is a huge topic. We will cover some of it in this chapter as well as in later chapters, but not all of it.
In the Hello world chapter, we saw a class used for the first time, since everything in C# is built upon classes. Let's expand our Hello world example with a class we built on our own.
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Car car; car = new Car("Red"); Console.WriteLine(car.Describe()); car = new Car("Green"); Console.WriteLine(car.Describe()); Console.ReadLine(); } } class Car { private string color; public Car(string color) { this.color = color; } public string Describe() { return "This car is " + Color; } public string Color { get { return color; } set { color = value; } } } }
Okay, lots of new stuff here, but almost all of it is based on stuff we've already used earlier in this tutorial. As you can see, we have defined a new class, called Car. It's declared in the same file as our main application, for an easier overview, however, usually new classes are defined in their own files. It defines a single variable, called color, which of course is used to tell the color of our car. We declared it as private, which is good practice - accessing variables from the outside should be done using a property. The Color property is defined in the end of the class, giving access to the color variable. Read: C Sharp
Besides that, our Car class defines a constructor. It takes a parameter which allows us to initialize Car objects with a color. Since there is only one constructor, Car objects can only be instantiated with a color. The Describe() method allows us to get a nice message with the single piece of information that we record about our. It simply returns a string with the information we provide.
Now, in our main application, we declare a variable of the type Car. After that, we create a new instance of it, with "Red" as parameter. According to the code of our class, this means that the color red will be assigned as the color of the car. To verify this, we call the Describe() method, and to show how easy we can create several instances of the same class, we do it again, but with another color. We have just created our first functional class and used it.
In the following chapters, concepts like properties, constructors and visibility will be explained in more depth.
0 notes