Tuesday, January 16, 2018

in Parameter

'in' used to pass read only reference of a variable.

1.Can be used to pass a variable as a reference (value type and reference type both).
2.Only for input not for output.
3."in variable" must be initialized before passing it as a parameter.
4. Can not be decalred inline.
5. It is not necessary to use them in a variabe before leaveing the control.
6. Value type vairable are passed as read only, While reference type variables properties can be change but you can not re-allocate them again.

class Program  
    {  
        static void Main(string[] args)  
        {  
            Product product = new Product();  
            Modify(in product);  
        }  
        public static void Modify(in Product product)  
        {  
            //product = new Product();  // not allowed
            product.ProductId = 101;  
            product.ProductName = "Laptop";  
            product.Price = 60000;  
            WriteLine($"Id: {product.ProductId} Name: {product.ProductName} Price: {product.Price}");  
        }  
    }  
    class Product  
    {  
        public int ProductId { get; set; }  
        public string ProductName { get; set; }  
        public decimal Price { get; set; }  
    }  

Below will give comiple time error because structure is value type and value type variables properties can not be change with in paramtere.

class Program  
    {  
        static void Main(string[] args)  
        {  
            Product product = new Product();  
            Modify(in product);  
        }  
        public static void Modify(in Product product)  
        {  
            //product = new Product();  
            product.ProductId = 101;  
            product.ProductName = "Laptop";  
            product.Price = 60000;  
            WriteLine($"Id: {product.ProductId} Name: {product.ProductName} Price: {product.Price}");  
        }  
    }  
    struct Product  
    {  
        public int ProductId { get; set; }  
        public string ProductName { get; set; }  
        public decimal Price { get; set; }  
    }  

Why we need another keyword 'in'.
The reason is that if we pass a value type variable without reference then each time a new copy will be created. So, it will take extra memory and performance will be slower.

So instead of passing a copy of value type, we can pass a read-only reference of a value type variable which will make it faster and will use less memory.

Source : http://www.c-sharpcorner.com/article/c-sharp-7-2-in-parameter-and-performance/

No comments:

Followers

Link