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

Unity 3D – CSharp – Event Functions – Inizialization – Update – GUI – Mouse – Physics

Unity 3D – CSharp – Event Functions – Inizialization – Update – GUI – Mouse – Physics

To create videogames Unity3D give us special functions to manage special operations as variable inizialization, updating, physic management.


using UnityEngine;
using System.Collections;

public class MyScript : MonoBehaviour
{

        // Initialization Events
        // ******************************************

	void Awake ()
	{
		// first inizialization
		Debug.Log("Awake called.");
	}
	
	
	void Start ()
	{
		// second inizialization
		Debug.Log("Start called.");
	}

        // Regular Update Events
        // ******************************************

	void FixedUpdate ()
	{
		// frame indipendent update
                // use this function to drive physic
		Debug.Log("FixedUpdate time :" + Time.deltaTime);
	}
	
	void Update ()
	{
		// update at every frame
		Debug.Log("Update time :" + Time.deltaTime);
	}

	void LateUpdate () 
	{
		// update at the end of the frame rendering
		Debug.Log("Late Update");
	}

        // GUI Events
        // ******************************************

        void OnGUI() 
        {
                // draw here labels, buttons and other Graphic User Interface elements
        	GUI.Label(labelRect, "Game Over");
        }

        // Mouse Events
        // ******************************************

        void OnMouseOver() 
        {
                // do something if mouse is over
        }

        void OnMouseDown() {
                // do something if mouse is down
        }

        // Physics Events
        // ******************************************

        void OnCollisionEnter(otherObj: Collision) 
        {
                // do stuff if there is a collision
        }

        void OnTriggerEnter(Collider other) 
        {
                // do stuff if there is an object that overlap the trigger
        }

} // END MyScript

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

Ref: http://docs.unity3d.com/Manual/EventFunctions.html

By |CSharp, Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – CSharp – Event Functions – Inizialization – Update – GUI – Mouse – Physics

Unity3D – C# – Basic Syntax

Unity3D – C# – Basic Syntax

First you need call basic namespace and nest all the code inside a class with the name of your script, see the example below.

Basic Structure

Project Window> RMB> Create> C#> name it ‘MyFirstScript’> double click to open ‘MonoDevelop’ editor


// call basic namespace of Unity3D
using UnityEngine;
using System.Collections;

// MonoBehaviour is the base class every script derives from
// class nameofmyscript : derived from MonoBehaviour
public class MyFirstScript : MonoBehaviour {

// Unity3D exclusive function - Use this for initialization
	void Start () {
	
	}// END Start()

	
// Unity3D exclusive function - Update is called once per frame
	void Update () {
	
	}// END Update()

}// END of class MyFirstScript

Variables and Fuctions


// call basic namespace of Unity3D
using UnityEngine;
using System.Collections;

// MonoBehaviour is the base class every script derives from
// scope class nameofmyscript : derived from MonoBehaviour
public class MyFirstScript : MonoBehaviour {
	
	// declare variables
	// scope type nameofvariable = value
	public int myInt = 5;   // you can setup it inside inspector
	private int myInt2 = 6;	// you can't setup it inside inspector
	
	// Unity3D exclusive function - Use this for initialization - void because it has no type
	void Start () {
		myInt = MultiplyByTwo(myInt);
		Debug.Log (myInt);
		
	}// END Start()
	
	// Your custom fuction
	// scope type functionname (type variable)
	public int MultiplyByTwo (int number)
	{
		int ret;
		ret = number * 2;
		return ret;
	}
	
	// Unity3D exclusive function - Update is called once per frame - void because it has no type
	void Update () {
		
	}// END Update()
	
}// END of class MyFirstScript

By |CSharp, Unity3D, Video Games Development|Commenti disabilitati su Unity3D – C# – Basic Syntax