Is it possible to assign a value to a const Variable when creating an Object?How to create a new object instance from a TypeWhat's the strangest corner case you've seen in C# or .NET?ISerializable: Assign an existing object on deserializationHow would you manage your constants for each c# class?How to create own dynamic type or dynamic object in C#?Creating constant objects in C# EF CodeFirst?How much should I enforce the concept of entity and value object in DDD?Is it possible to get the object from debug mode as string?How to create a single object and use values in different events?AutoMapper creates objects of Internal classes, how is that?

Arithmetics in LuaLaTeX

What is the period of Langton's ant on a torus?

Why won't some unicode characters print to my terminal?

How can I help our ranger feel special about her beast companion?

Zhora asks Deckard: "Are you for real?". Was this meant to be significant?

Why jet engines sound louder on the ground than inside the aircraft?

ANOVA or Linear Mixed Model?

How do you send money when you're not sure it's not a scam?

Is Error correction and detection can be done with out adding extra bits?

Did Hitler say this quote about homeschooling?

When can a polynomial be written as a polynomial function of another polynomial?

Difference between c++14 and c++17 using: `*p++ = *p`

is 1hr 15 minutes enough time to change terminals at Manila?

Inscriptio Labyrinthica

When is the Circle of Dreams druid's Walker in Dreams feature used?

Is encryption still applied if you ignore the SSL certificate warning for self signed?

Last-minute canceled work-trip mean I'll lose thousands of dollars on planned vacation

Why don't humans perceive waves as twice the frequency they are?

What are the basics of commands in Minecraft Java Edition?

How can electric field be defined as force per charge, if the charge makes its own, singular electric field?

When designing an adventure, how can I ensure a continuous player experience in a setting that's likely to favor TPKs?

What makes MOVEQ quicker than a normal MOVE in 68000 assembly?

Is surviving this (blood loss) scenario possible?

Practical example in using (homotopy) type theory



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


How to create a new object instance from a TypeWhat's the strangest corner case you've seen in C# or .NET?ISerializable: Assign an existing object on deserializationHow would you manage your constants for each c# class?How to create own dynamic type or dynamic object in C#?Creating constant objects in C# EF CodeFirst?How much should I enforce the concept of entity and value object in DDD?Is it possible to get the object from debug mode as string?How to create a single object and use values in different events?AutoMapper creates objects of Internal classes, how is that?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















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 ?










share|improve this question

















  • 2





    How about using readonly?

    – Patrick
    Mar 26 at 10:04












  • Oh. I didn't know about that since I'm pretty new to this.

    – Artistic Aligator
    Mar 26 at 10:05

















1















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 ?










share|improve this question

















  • 2





    How about using readonly?

    – Patrick
    Mar 26 at 10:04












  • Oh. I didn't know about that since I'm pretty new to this.

    – Artistic Aligator
    Mar 26 at 10:05













1












1








1








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 ?










share|improve this question














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 ?







c#






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 10:03









Artistic AligatorArtistic Aligator

1101 silver badge11 bronze badges




1101 silver badge11 bronze badges







  • 2





    How about using readonly?

    – Patrick
    Mar 26 at 10:04












  • Oh. I didn't know about that since I'm pretty new to this.

    – Artistic Aligator
    Mar 26 at 10:05












  • 2





    How about using readonly?

    – Patrick
    Mar 26 at 10:04












  • Oh. I didn't know about that since I'm pretty new to this.

    – Artistic Aligator
    Mar 26 at 10:05







2




2





How about using readonly?

– Patrick
Mar 26 at 10:04






How about using readonly?

– Patrick
Mar 26 at 10:04














Oh. I didn't know about that since I'm pretty new to this.

– Artistic Aligator
Mar 26 at 10:05





Oh. I didn't know about that since I'm pretty new to this.

– Artistic Aligator
Mar 26 at 10:05












2 Answers
2






active

oldest

votes


















2














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#






share|improve this answer























  • Is there a way to do all that from a Set Function? Since readonly also seems to only be writable from the constructor.

    – Artistic Aligator
    Mar 26 at 10:10











  • @ArtisticAligator - like from a setter? Is your case that you do not know when you want to initialize it but that you want only once?

    – Gilad Green
    Mar 26 at 10:13











  • No that would not be because of the time I want to set it but because of keeping the size of the constructor comprehensible.

    – Artistic Aligator
    Mar 26 at 10:15






  • 1





    @ArtisticAligator - if it is big it is probably doing too much. Think if you could use multiple ctors where one calls another. If not then you could also create some private functions and call them from the ctor. Still I'd say that if the ctor is doing so much it is probably doing stuff it shouldn't

    – Gilad Green
    Mar 26 at 10:20






  • 1





    @ArtisticAligator - you are welcome :)

    – Gilad Green
    Mar 26 at 10:45


















1














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.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55354352%2fis-it-possible-to-assign-a-value-to-a-const-variable-when-creating-an-object%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    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#






    share|improve this answer























    • Is there a way to do all that from a Set Function? Since readonly also seems to only be writable from the constructor.

      – Artistic Aligator
      Mar 26 at 10:10











    • @ArtisticAligator - like from a setter? Is your case that you do not know when you want to initialize it but that you want only once?

      – Gilad Green
      Mar 26 at 10:13











    • No that would not be because of the time I want to set it but because of keeping the size of the constructor comprehensible.

      – Artistic Aligator
      Mar 26 at 10:15






    • 1





      @ArtisticAligator - if it is big it is probably doing too much. Think if you could use multiple ctors where one calls another. If not then you could also create some private functions and call them from the ctor. Still I'd say that if the ctor is doing so much it is probably doing stuff it shouldn't

      – Gilad Green
      Mar 26 at 10:20






    • 1





      @ArtisticAligator - you are welcome :)

      – Gilad Green
      Mar 26 at 10:45















    2














    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#






    share|improve this answer























    • Is there a way to do all that from a Set Function? Since readonly also seems to only be writable from the constructor.

      – Artistic Aligator
      Mar 26 at 10:10











    • @ArtisticAligator - like from a setter? Is your case that you do not know when you want to initialize it but that you want only once?

      – Gilad Green
      Mar 26 at 10:13











    • No that would not be because of the time I want to set it but because of keeping the size of the constructor comprehensible.

      – Artistic Aligator
      Mar 26 at 10:15






    • 1





      @ArtisticAligator - if it is big it is probably doing too much. Think if you could use multiple ctors where one calls another. If not then you could also create some private functions and call them from the ctor. Still I'd say that if the ctor is doing so much it is probably doing stuff it shouldn't

      – Gilad Green
      Mar 26 at 10:20






    • 1





      @ArtisticAligator - you are welcome :)

      – Gilad Green
      Mar 26 at 10:45













    2












    2








    2







    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#






    share|improve this answer













    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#







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 26 at 10:05









    Gilad GreenGilad Green

    31.2k5 gold badges35 silver badges60 bronze badges




    31.2k5 gold badges35 silver badges60 bronze badges












    • Is there a way to do all that from a Set Function? Since readonly also seems to only be writable from the constructor.

      – Artistic Aligator
      Mar 26 at 10:10











    • @ArtisticAligator - like from a setter? Is your case that you do not know when you want to initialize it but that you want only once?

      – Gilad Green
      Mar 26 at 10:13











    • No that would not be because of the time I want to set it but because of keeping the size of the constructor comprehensible.

      – Artistic Aligator
      Mar 26 at 10:15






    • 1





      @ArtisticAligator - if it is big it is probably doing too much. Think if you could use multiple ctors where one calls another. If not then you could also create some private functions and call them from the ctor. Still I'd say that if the ctor is doing so much it is probably doing stuff it shouldn't

      – Gilad Green
      Mar 26 at 10:20






    • 1





      @ArtisticAligator - you are welcome :)

      – Gilad Green
      Mar 26 at 10:45

















    • Is there a way to do all that from a Set Function? Since readonly also seems to only be writable from the constructor.

      – Artistic Aligator
      Mar 26 at 10:10











    • @ArtisticAligator - like from a setter? Is your case that you do not know when you want to initialize it but that you want only once?

      – Gilad Green
      Mar 26 at 10:13











    • No that would not be because of the time I want to set it but because of keeping the size of the constructor comprehensible.

      – Artistic Aligator
      Mar 26 at 10:15






    • 1





      @ArtisticAligator - if it is big it is probably doing too much. Think if you could use multiple ctors where one calls another. If not then you could also create some private functions and call them from the ctor. Still I'd say that if the ctor is doing so much it is probably doing stuff it shouldn't

      – Gilad Green
      Mar 26 at 10:20






    • 1





      @ArtisticAligator - you are welcome :)

      – Gilad Green
      Mar 26 at 10:45
















    Is there a way to do all that from a Set Function? Since readonly also seems to only be writable from the constructor.

    – Artistic Aligator
    Mar 26 at 10:10





    Is there a way to do all that from a Set Function? Since readonly also seems to only be writable from the constructor.

    – Artistic Aligator
    Mar 26 at 10:10













    @ArtisticAligator - like from a setter? Is your case that you do not know when you want to initialize it but that you want only once?

    – Gilad Green
    Mar 26 at 10:13





    @ArtisticAligator - like from a setter? Is your case that you do not know when you want to initialize it but that you want only once?

    – Gilad Green
    Mar 26 at 10:13













    No that would not be because of the time I want to set it but because of keeping the size of the constructor comprehensible.

    – Artistic Aligator
    Mar 26 at 10:15





    No that would not be because of the time I want to set it but because of keeping the size of the constructor comprehensible.

    – Artistic Aligator
    Mar 26 at 10:15




    1




    1





    @ArtisticAligator - if it is big it is probably doing too much. Think if you could use multiple ctors where one calls another. If not then you could also create some private functions and call them from the ctor. Still I'd say that if the ctor is doing so much it is probably doing stuff it shouldn't

    – Gilad Green
    Mar 26 at 10:20





    @ArtisticAligator - if it is big it is probably doing too much. Think if you could use multiple ctors where one calls another. If not then you could also create some private functions and call them from the ctor. Still I'd say that if the ctor is doing so much it is probably doing stuff it shouldn't

    – Gilad Green
    Mar 26 at 10:20




    1




    1





    @ArtisticAligator - you are welcome :)

    – Gilad Green
    Mar 26 at 10:45





    @ArtisticAligator - you are welcome :)

    – Gilad Green
    Mar 26 at 10:45













    1














    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.






    share|improve this answer



























      1














      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.






      share|improve this answer

























        1












        1








        1







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 10:05









        StuartStuart

        2,2451 gold badge14 silver badges41 bronze badges




        2,2451 gold badge14 silver badges41 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55354352%2fis-it-possible-to-assign-a-value-to-a-const-variable-when-creating-an-object%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript