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

Saturday 11 September 2021

init only property in c#9 or later versions

 c# 9 introduces new Init-Only property that allow to make immutable properties in a class. This means the property with "init" keyword in place of "set" keyword allows the property to be initialized at the construction step of an object. it doesn't allow you to set the value later, once the object is initialised. 

For example

 public class Friend

        {

            public Friend(string name, string surname)

            {

                this.Name = name;

                this.Surname = surname;

            }

            public string Name { get; init; }


            public string Surname { get; init; }

        }


Use of Friend

   public void SomeMethod()

        {

            Friend friend = new Friend("John", "Sharma");

            var newFriend = new Friend("Tom", "Pandey");

        }

Use of init property after initialization throws an error. for eg.

 public void SomeMethod()

        {

            Friend friend = new Friend("John", "Sharma");

            var newFriend = new Friend("Tom", "Pandey");

            friend.Surname = "xxx"; //<--- Error here.

        }

Generate SQL script from entity framework using powershell/visual studio

to run the below command , start PowerShell in visual studio. Select the database project. In PowerShell:   Script-Migration this command wi...