Video Games Development

CSharp – Static Polymorphism – Function Overloading

CSharp – Static Polymorphism – Function Overloading

Polymorphism is a Greek word that means “many-shaped”
With Function Overloading you can have multiple definitions for the same function name in the same scope.
Same name for the function, many-shaped variables.


using System;

namespace ConsoleApplication1
{

    class Printdata
    {
        void print(int i)
        {
            Console.WriteLine("Printing int: {0}", i);
        }

        void print(double f)
        {
            Console.WriteLine("Printing float: {0}", f);
        }

        void print(string s)
        {
            Console.WriteLine("Printing string: {0}", s);
        }
        static void Main(string[] args)
        {
            Printdata p = new Printdata();
            // Call print to print integer
            p.print(5);
            // Call print to print float
            p.print(500.263);
            // Call print to print string
            p.print("Hello C++");
            Console.ReadKey();
        }
    }

}

The result is:

Printing int: 5
Printing float: 500.263
Printing string: Hello C++

For italian people: come funziona?
C# distingue automaticamente la funzione chiamata in base alle variabili che gli vengono spedite, quindi:
p.print(5); -> void print(int i)
p.print(500.263); -> void print(double f)
p.print(“Hello C++”); -> void print(string s)

By |CSharp|Commenti disabilitati su CSharp – Static Polymorphism – Function Overloading

CSharp – Inheritance

CSharp – Inheritance

Inheritance (Ereditarietà) allows us to define a class in terms of another class, which makes it easier to create and maintain an application.

When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

The derived class inherits the base class member variables and member methods.

Syntax


<acess-specifier> class <base_class>
{
 ...
}
class <derived_class> : <base_class>
{
 ...
}

Example


using System;
namespace InheritanceApplication
{
   // Base Class
   class Shape 
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // Derived class
   class Rectangle: Shape
   {
      public int getArea()
      { 
         return (width * height); 
      }
   }
   
   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle Rect = new Rectangle(); // Declare Rect of type Rectangle

         Rect.setWidth(5);
         Rect.setHeight(7);

         // Print the area of the object.
         Console.WriteLine("Total area: {0}",  Rect.getArea());
         Console.ReadKey();
      }
   }
}

The result is:

Total area: 35

For italian people: come funziona?
1. la funzine Main() è la prima ad essere eseguita
2. Rectangle Rect = new Rectangle(); -> dichiaro Rect di tipo classe Rectangle
3. Rect.setWidth(5); -> invio alla classe Rectangle, funzione setWidth() il valore 5
4. la funzione setWidth() è stata ereditata dalla classe Shape, infatti…
5. class Rectangle: Shape -> la classe Rectangle è derivata dalla classe base Shape dalla quale ne eredita le funzioni
6. Rect.setHeight(7); -> come per il punto 4. e 5. viene settata la variabile height = h;
7. Rect.getArea() -> calcola l’area -> return (width * height);

I vantaggi che porta una struttura che utilizza l’ereditarietà delle classi è che il codice risulta più facile da mantenere e modificare rispetto ad una struttura con una singola classe. Ovviamente tutto questo ha senso se il nostro codice necessita di classi complesse, non di una struttura semplice come quella riportata nell’esempio sopra.

My website: http://www.lucedigitale.com

Ref: http://www.tutorialspoint.com/csharp/csharp_inheritance.htm

By |CSharp|Commenti disabilitati su CSharp – Inheritance

CSharp – Classes – Constructors – Destructors – Static

CSharp – Classes – Constructors – Destructors – Static

Classes are an expanded concept of data structures (struct): like data structures, they can contain data members, but they can also contain functions as members.

Class Definition

Syntax:


<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 variables from a class


using System;
namespace BoxApplication
{
    class Box
    {
       public double length;   // Length of a box
       public double breadth;  // Breadth of a box
       public double height;   // Height of a box
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // Declare Box1 of type Box
            Box Box2 = new Box();        // Declare Box2 of type Box
            double volume = 0.0;         // Store the volume of a box here

            // box 1 specification
            Box1.height = 5.0;
            Box1.length = 6.0;
            Box1.breadth = 7.0;

            // box 2 specification
            Box2.height = 10.0;
            Box2.length = 12.0;
            Box2.breadth = 13.0;
           
            // volume of box 1
            volume = Box1.height * Box1.length * Box1.breadth;
            Console.WriteLine("Volume of Box1 : {0}",  volume);

            // volume of box 2
            volume = Box2.height * Box2.length * Box2.breadth;
            Console.WriteLine("Volume of Box2 : {0}", volume);
            Console.ReadKey();
        }
    }
}

Notice:


Box Box1 = new Box(); 
...
Box1.height = 5.0;

The result is:

Volume of Box1 : 210
Volume of Box2 : 1560

For italian peolple: come funziona?
1. carico il namespace (raccolta di classi e funzioni) -> using System
2. incapsulo tutto il codice in un namespace con il nome del mio file c# -> namespace BoxApplication
3. creo la classe Box e dichiaro le variabili della classe Box -> length, breadth, height.
4. creo la classe Boxtester, con all’interno la funzione Main(), che è la prima che viene eseguita da c#
5. quando viene eseguita Main()dichiaro che Box1 è una variabile della classe Box -> Box Box1 = new Box()
6. quindi può essere associata alle variabili della classe Box -> Box1.height = 5.0; – Box1.length = 6.0; – Box1.breadth = 7.0;
7. eseguo le operazioni per il valcolo del volume

Using functions from a class


using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line()
      {
         Console.WriteLine("Object is being created");
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line(); // Declare line of type Line   
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

Notice:


Line line = new Line(); 
...
line.setLength(6.0);

The result is:

Object is being created
Length of line : 6

Constructors and Destructors

A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope. A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters.

Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc. Destructors cannot be inherited or overloaded.


using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line()  // constructor
      {
         Console.WriteLine("Object is being created");
      }
      ~Line() //destructor
      {
         Console.WriteLine("Object is being deleted");
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());           
      }
   }
}

The result is:

Object is being created
Length of line : 6
Object is being deleted

For italian people: come funziona?
Quando a funzione Line() ha esaurito la sua utilità, ~Line() la distrugge (Destructor) per liberare risorse hardware.

Static

We can define class members as static using the static keyword. When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member.


using System;
namespace StaticVarApplication
{
    class StaticVar
    {
        public static int num; // notice static keyword
        public void count()
        {
            num++;
        }
        public int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s1 = new StaticVar();
            StaticVar s2 = new StaticVar();
            s1.count();
            s1.count();
            s1.count();
            s2.count();
            s2.count();
            s2.count();         
            Console.WriteLine("Variable num for s1: {0}", s1.getNum());
            Console.WriteLine("Variable num for s2: {0}", s2.getNum());
            Console.ReadKey();
        }
    }
}

The result is:

Variable num for s1: 6
Variable num for s2: 6

If you remove static:


using System;
namespace StaticVarApplication
{
    class StaticVar
    {
        public int num; // notice static keyword
        public void count()
        {
            num++;
        }
        public int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s1 = new StaticVar();
            StaticVar s2 = new StaticVar();
            s1.count();
            s1.count();
            s1.count();
            s2.count();
            s2.count();
            s2.count();         
            Console.WriteLine("Variable num for s1: {0}", s1.getNum());
            Console.WriteLine("Variable num for s2: {0}", s2.getNum());
            Console.ReadKey();
        }
    }
}

The result is:

Variable num for s1: 3
Variable num for s2: 3

By |CSharp|Commenti disabilitati su CSharp – Classes – Constructors – Destructors – Static

CSharp – Structure

CSharp – Structure

A data structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths.

Notice that:
– structures do not support inheritance
– structures cannot have default constructor


using System;

namespace ConsoleApplication1
{

    struct Books
    {
        public string title;
        public string author;
        public string subject;
        public int book_id;
    };

    public class testStructure
    {
        public static void Main(string[] args)
        {

            Books Book1;        /* Declare Book1 of type Book */
            Books Book2;        /* Declare Book2 of type Book */

            /* book 1 specification */
            Book1.title = "C Programming";
            Book1.author = "Nuha Ali";
            Book1.subject = "C Programming Tutorial";
            Book1.book_id = 6495407;

            /* book 2 specification */
            Book2.title = "Telecom Billing";
            Book2.author = "Zara Ali";
            Book2.subject = "Telecom Billing Tutorial";
            Book2.book_id = 6495700;

            /* print Book1 info */
            Console.WriteLine("Book 1 title : {0}", Book1.title);
            Console.WriteLine("Book 1 author : {0}", Book1.author);
            Console.WriteLine("Book 1 subject : {0}", Book1.subject);
            Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);

            /* print Book2 info */
            Console.WriteLine("Book 2 title : {0}", Book2.title);
            Console.WriteLine("Book 2 author : {0}", Book2.author);
            Console.WriteLine("Book 2 subject : {0}", Book2.subject);
            Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);

            Console.ReadKey();

        } // END Main
    } // END testStructure
}

The result is:

Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

By |CSharp|Commenti disabilitati su CSharp – Structure

CSharp – Functions

CSharp – Functions

A function allows you to encapsulate a piece of code and call it from other parts of your code.

Syntax:


<visibility> <return type> <method name>(<parameters>)
{
	<function code>
}

Example:

...
public int AddNumbers(int number1, int number2)
{
    int result = number1 + number2;
    return result;
}
...
int result = AddNumbers(10, 5);
Console.WriteLine(result);
...
By |CSharp|Commenti disabilitati su CSharp – Functions