Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday 26 May 2021

FlagsAttributes in C#

 Introduction

    In C# enum is a named integer constant. But a type can have only one enum value. FlagsAttribute is used to assign multiple enum values.

Example

using System;

public class Program

{

public static void Main()

{

var rocky = new Person("Rock", Vehicle.BMWX5);

var peter = new Person("Peter Parker", Vehicle.Highlander);

rocky.PersonInfo();

            //Output: Rock owns BMWX5

peter.PersonInfo();

            //Output: Peter Parker owns Highlander

}

}

public class Person

{

public string Name{get;set;}

public Vehicle Vehicle{get;set;}

public Person(string name, Vehicle vehicle)

{

Name = name;

Vehicle=vehicle;

}

public void PersonInfo()

{

Console.WriteLine($"{Name} owns {Vehicle}");

}

}

public enum Vehicle

{

none=0,

BMWX5=1,

LandRover=2,

LincolnAviator=4,

Highlander=8

}

In the above program, one person can own one vehicle.

What if a person owns 2 or more vehicles. In this case FlagsAttribute is useful.

using System;

public class Program

{

public static void Main()

{

                //vehicle2 is now represents 2 vehicles BMWX5 and Highlander both.

var vehicle2 = Vehicle.BMWX5|Vehicle.Highlander;

     var rocky = new Person("Rock", Vehicle.BMWX5);

var peter = new Person("Peter Parker", Vehicle.Highlander);

                // John owns vehicle2 means he has 2 vehicles.

var john = new Person("John", vehicle2);

rocky.PersonInfo();

peter.PersonInfo();

john.PersonInfo();

                //Output: John owns BMWX5, Highlander

}

}


public class Person

{

public string Name{get;set;}

public Vehicle Vehicle{get;set;}

public Person(string name, Vehicle vehicle)

{

Name = name;

Vehicle=vehicle;

}

public void PersonInfo()

{

Console.WriteLine($"{Name} owns {Vehicle}");

}

}

[Flags]

public enum Vehicle

{

none=0,

BMWX5=1,

LandRover=2,

LincolnAviator=4,

Highlander=8

}  

Complete Code


Thursday 22 May 2014

C# Lazy Initialization or Instantiation

Introduction: 

Sometime we want to defer or delay the initialization of the resource intensive or large object in case if it is not required at the moment to improve the performance or response time of the application.
Microsoft C# 4.0 introduced new feature Lazy<T> to achieve the above behavior. 

Lazy<T> defers or delay the creation of a large or resource-intensive object, or the execution of a resource-intensive task. It creates the instance of the object when it is first time used or called in the application.

Lazy<T> Properties:


It has 2 properties
  • IsValueCreated: It is boolean type property which return true if object is instanciated and false if not.
  • Value: It returns the object of type T.

Now I am going to create one sample application to demonstrate how to use it.

Step 1. Create one C# Console LazyInitialization application.
Step 2. Open the Program file and add below 2 classes inside the same namespace.


  public class Order

    {
       public Order()
      {
         this.OrderId=1234;
         this.DeliveryDate = DateTime.Today;
         this.OrderCreationDate = DateTime.Today.AddDays(-2);
      }

        public int OrderId { get; set; }


        public DateTime DeliveryDate { get; set; }        

        public DateTime OrderCreationDate { get; set; }
    
    }
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Lazy<Order> OrderInformation { get; set; }
    }



Customer class has an aggregation with Order. 
Initialization of the Order object will be deferred and it will only get initialized when it will be demanded first time in the application.

Now update the main method as shown below


 static void Main(string[] args)
        {
            Customer customer = new Customer();
            customer.FirstName = "Joe";
            customer.LastName = "Mackenzy";           
            customer.OrderInformation = new Lazy<Order>(); 

            Console.WriteLine("Customer Name:{0}", customer.FirstName + " " + customer.LastName);
            Console.WriteLine("Customer's Order isCreated: {0}", customer.OrderInformation.IsValueCreated);

            var customerOrder = customer.OrderInformation.Value;

            Console.WriteLine("Customer's Order isCreated: {0}", customer.OrderInformation.IsValueCreated);
            Console.WriteLine("Customer's Order ID: {0} Delivery Date: {1}", customerOrder.OrderId, customerOrder.DeliveryDate);
            Console.Read();
        }



it will output as  below








Primitive DataType:

Below I am going to illustrate for int data type.

 static void Main(string[] args)
        {
            int z = 0;
           
            Lazy<int> lazyint = new Lazy<int>(() => { z = 10; return z; });
            Console.WriteLine(string.Format("Value of z: {0}", z));
            var zValue = lazyint.Value;
            Console.WriteLine(string.Format("Value of z: {0}", zValue));
            Console.Read();

        }

In the above program z is an integer type variable with value 0. 
now z is initialized with Lazy object and inside anonymous method value of z is set to 10 which is a parameter of Lazy constructor.

so value of z is set to 10 after referring Value property of lazyint when it is being actually used. 

Output:
Value of z: 0
Value of z: 10.



Note: Refer MSDN for multithread usage.