What is difference between const & readonly keywords in C#?

Dung Do Tien Oct 25 2021 36

Hello, I see my project in my company, someone usually write code as below:

private const int _timeInterval = 100;
private const int _timeFixedDefault = 150;
private readonly IMemberBoFE _memberBoFE;
private readonly UserManager<MemberAppUser> _userManager;
private readonly SignInManager<MemberAppUser> _signInManager;
public AccountController(IMemberBoFE memberBoFE, SignInManager<MemberAppUser> signInManager, UserManager<MemberAppUser> userManager)
{
    _memberBoFE = memberBoFE;
    _signInManager = signInManager;
    _userManager = userManager;
}

It's really difficult to understand some variables using keyword const and some other use readonly

Anyone can explain What is difference between const & readonly keywords in C#? And C# required to use them?

Thanks for any explanation.

Have 2 answer(s) found.
  • A

    Armin Habibi Oct 25 2021

    Const

    - It is mandatory to initialize the variable at the time of its declaration. But value must be fixed not get from dynamic, ex: 1,2, 4.65, "Hello world".
    - It defaults to a static
    - It is usually used for a variable value type.
    - Variable can not change the value after it's declared.

    Readonly

    - The read-only variable’s value cannot be modified once after its initialization. (after object instance)
    - Readonly is usually used to create an instance for a class, object.

  • A

    An Pham Truong Oct 25 2021

    - Const is only used for value type variables such as int, string, bool, datetime....

    - Readonly can use for all value types and reference types.

    - Const doesn't allow change value after declare.

    - Readyonly not allow change after class is instanced.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close