Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Lesson 4

Learn C#

  • Login to see the comments

  • Be the first to like this

Lesson 4

  1. 1. Lesson 4 Learn C#. Series of C# lessons
  2. 2. Agenda • Classes • Functions/Methods • Properties
  3. 3. Class example • Constructors • Static constructors • Access modifiers • static
  4. 4. Constructor • Constructors are used to create and initialize any object member variables when you use the 'new' expression to create an object of a class.
  5. 5. Functions/Methods • A function allows you to encapsulate a piece of code and call it from other parts of your code. <visibility> <return type> <Name>(<parameters>) { <function code> return <returned object>; }
  6. 6. Preperties • A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. class User { private string _country;//backed field public string FirstName { get; set; }//backed field will be created automatically public string LastName { get; set; } public string FullName => FirstName + " " + LastName; //Read only property public bool IsInitialized // ReadOnly property { get { return !string.IsNullOrEmpty(FirstName) && !string.IsNullOrEmpty(LastName); } } public string Country//property using backed field { get { return string.Format("I live in {0}", _country); } set { _country = value; } } }
  7. 7. Access modifiers • public: access is not restricted • private: access is limited to the containing type • protected: access is limited to the containing class or types derived from the containing class • internal: access is limited to the current assembly • protected internal: access is limited to the current assembly or types derived from the containing class
  8. 8. static • static function • static property • static class class Animal { public static int AnimalCount { get; private set; } private string Name; public Animal() { Name = "No name defined."; AnimalCount++; } public Animal(string name) { Name = name; AnimalCount++; } public void PrintName() { Console.WriteLine(Name); } public static void GetInfo() { Console.WriteLine("My mission is to be an animal"); } } Animal.GetInfo(); //prints message Animal a1 = new Animal(); Animal a2 = new Animal("Cow"); Animal a3 = new Animal(); a2.PrintName();//prints Cow a3.PrintName();// pring 'no name defined' message Console.WriteLine(Animal.AnimalCount); // outputs 3
  9. 9. Static constructor • A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
  10. 10. Thank you! Questions?