programmazione

CSharp – Properties – get-set

CSharp – Properties – get-set

Properties allow you to control the accessibility of a classes variables.
A property consists of 2 parts, a get and a set method, wrapped inside the property.
Only one method is required, this allows you to define read-only and write-only properties.

Syntax:

...

// la proprietà è la stringa Color
public string Color
{
    // get restituisce il valore di una variabile
    get { return color; }

    // set assegna a color il valore  - keyword value - proveniente dall'esterno 
    set { color = value; }
}
...

Example:


// definisco la proprietà Color come pubblica e di tipo stringa
public string Color
{
    get 
    {
        return color.ToUpper(); // converte una stringa in caratteri maiuscoli
    }
    set 
    { 
        if(value == "Red")
            color = value; // keyword value assegna il valore proveniente dall'esterno a color
        else
            Console.WriteLine("This car can only be red!");
    }
}

For italian people: come funziona?
1. if(value == “Red”) -> se la variabile è uguale a ‘Red’ -> set -> color = Red
2. get -> ritorna ‘RED’

Example:


class TimePeriod
{
    private double seconds;

    // proprietà - double Hours -
    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}


class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}
// Output: Time in hours: 24

For italian people: come funziona?
1. si avvia Main()
2. dichiato ‘t’ come variabile di tipo TimePeriod, la sintassi è la stessa che uso per richiamare una funzione
3. t.Hours = 24; -> assegnare un valore a ‘Hours’ causa l’avvio di ‘set’ che memorizza i dati in secondi
4. restituisce ‘get’ -> restituisce i dati in ore
5. System.Console.WriteLine(“Time in hours: ” + t.Hours); -> t.Hours è quello restituito da get

Example:


// Declare a Code property of type string:
public string Code
{
   get
   {
      return code;
   }
   set
   {
      code = value;
   }
}

// Declare a Name property of type string:
public string Name
{
   get
   {
     return name;
   }
   set
   {
     name = value;
   }
}

// Declare a Age property of type int:
public int Age
{ 
   get
   {
      return age;
   }
   set
   {
      age = value;
   }
}

Working Example:


using System;
namespace tutorialspoint
{
   class Student
   {

      private string code = "N.A";
      private string name = "not known";
      private int age = 0;

      // Declare a Code property of type string:
      public string Code
      {
         get
         {
            return code;
         }
         set
         {
            code = value;
         }
      }
   
      // Declare a Name property of type string:
      public string Name
      {
         get
         {
            return name;
         }
         set
         {
            name = value;
         }
      }

      // Declare a Age property of type int:
      public int Age
      {
         get
         {
            return age;
         }
         set
         {
            age = value;
         }
      }
      public override string ToString()
      {
         return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
      }
    }
    class ExampleDemo
    {
      public static void Main()
      {
         // Create a new Student object:
         Student s = new Student();
            
         // Setting code, name and the age of the student
         s.Code = "001";
         s.Name = "Zara";
         s.Age = 9;
         Console.WriteLine("Student Info: {0}", s);
         //let us increase age
         s.Age += 1;
         Console.WriteLine("Student Info: {0}", s);
         Console.ReadKey();
       }
   }
}

The result is:

Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10

For italian people: come funziona?
1. si avvia per prima Main()
2. Student s = new Student(); -> dichiaro l’oggetto s di tipo Student()
3. s.Code = “001”; -> avvia ‘class Studen’t> proprietà ‘Code’> set> code=001
4. get -> ritorna il valore code=001, quindi al di fuori di ‘class Student’ la proprietà Code=001

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

By |CSharp|Commenti disabilitati su CSharp – Properties – get-set

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

C++ Enum

C++ Enum

Quando si definisce una variabile di tipo enumerativo, ad essa viene associato un insieme di costanti intere chiamato insieme dell’enumerazione. La variabile può contenere una qualsiasi delle costanti definite.

enum


// Sintassi
enum type_name {
  value1,
  value2,
  value3,
  .
  .
} object_names;


// 1. definiamo secchio come un tipo di dati enum
// all'interno indico il valore delle costanti
enum secchio {
    VUOTO,
    MEZZO_PIENO,
    PIENO = 5
} mio_secchio;

// 2. poi possiamo definire:
secchio tuo_secchio;
// oppure in modo equivalente
enum secchio tuo_secchio;

// 3. poi posso assegnare i valori delle costanti
// NON POSSO ASSEGNARE VALORI AL DI FUORI DELLE COSTANTI
mio_secchio = PIENO;
tuo_secchio = VUOTO;

Un’altro esempio:
creo un tipo di variabile colors_t dove immagazzinare i colori.

...
enum colors_t {black, blue, green, cyan, red, purple, yellow, white};
...

enum class

Con ‘enum class’ possiamo dichiarare non solo interi, ma anche altri tipi di dato.

...
enum class EyeColor : char {blue, green, brown}; 
...

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

Reference: http://www.cplusplus.com/doc/tutorial/other_data_types/
Reference: http://www.html.it/pag/15478/gli-identificatori/

By |C++, Video Games Development|Commenti disabilitati su C++ Enum