zebck
zebck

Reputation: 334

Is it possible to assign a value to a const Variable when creating an Object?

I am creating a Client for a WebRequestTool which contains a Token that is used throughout the lifetime of each Object but is unique to each entity of the class. Since I do not want that value to be changeable after an Object is created, I would like it to be Constant.

I already tried using an internal SetMethod which is called from the constructor like :

internal void setToken(string token)
{
    this.TOKEN = token; 
}

I also tried just assigning it inside the constructor. That is also not working.

public class Client
{
    const TOKEN; 

    public client(string token)
    {
      this.TOKEN = token;
    }
}

Is there really no other way of assigning a constant than hardcoding it when declaring it? And if there is what is it ?

Upvotes: 1

Views: 1048

Answers (2)

Gilad Green
Gilad Green

Reputation: 37299

From documentation:

A const field can only be initialized at the declaration of the field

You might want to use readonly instead:

A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used

Another nice resource: Difference between readonly and const keyword in C#

Upvotes: 2

Stuart
Stuart

Reputation: 4258

You can insted declare it private readonly

public class Client
{
   private readonly string _token;

   public Client(string token)
   {
       _token = token;
   }
}

Readonly fields can't be modified once they are set and can be set in the constructor.

Upvotes: 1

Related Questions