Advertisement
Stephen_MS

TOOL: Class - example

Nov 6th, 2015
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ex01_Dog_class_example
  8. {
  9.     // Class declaration
  10.     public class Dog
  11.     {   // Opening brace of the class body
  12.  
  13.         // Field declaration
  14.         private string name;
  15.  
  16.         // Constructor declaration
  17.         public Dog()
  18.         {
  19.             this.name = "Balkan";
  20.         }
  21.  
  22.         // Another constructor declaration
  23.         public Dog(string name)
  24.         {
  25.             this.name = name;
  26.         }
  27.  
  28.         // Property declaration
  29.         public string Name
  30.         {
  31.             get { return name; }
  32.             set { name = value; }
  33.         }
  34.  
  35.         // Method declaration
  36.         public void Bark()
  37.         {
  38.             Console.WriteLine("{0} said: Wow-wow!", name);
  39.         }
  40.     }   // Closing brace of te class body
  41.    
  42.  
  43.  
  44.     class Program
  45.     {
  46.         static void Main()
  47.         {
  48.             string firstDogName = null;
  49.             Console.WriteLine("Write first dog name: ");
  50.             firstDogName = Console.ReadLine();
  51.  
  52.             // Using a constructor to create a dog with specified name
  53.             Dog firstDog = new Dog(firstDogName);
  54.  
  55.             // Using a constructor to create a dog with a default name
  56.             Dog secondDog = new Dog();
  57.  
  58.             Console.WriteLine("Write second dog name: ");
  59.             string secondDogName = Console.ReadLine();
  60.  
  61.             // Using property to set the name of the dog
  62.             secondDog.Name = secondDogName;
  63.  
  64.             // Creatin a dog with a default name
  65.             Dog thirdDog = new Dog();
  66.  
  67.             Dog[] dogs = new Dog[] { firstDog, secondDog, thirdDog };
  68.  
  69.             foreach (Dog dog in dogs)
  70.             {
  71.                 dog.Bark();
  72.             }
  73.         }
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement