usage of const

Hi all, I am a beginner of C# language and have a question about const.

Does C# allow to  use const keyword to parameter option like C/C++

After trying several times, I wonder that C# doesn't.

If so, aren't  there ways to avoid the code like this :

class Hoge {

  .... methods or something are declared...

}

class HogeHoge {

  public UseHoge( ref Hoge h ) {

    h.someproperty = 12345;     // not problem to change some properties of h

    h = new Hoge();                    // this may be a mistake.

 }

HogeHoge.UseHoge() doesn't always be good.

I think there will be situations that I want to make sure that the methods

never replace the address of referrence type objects in them.

thanks. 

 



Answer this question

usage of const

  • Philip Harris

    In addition to the (correct) reply you got, one thing that bit me early on is that C# has const, but it's not the same.  const is for compile time values.  If you want to const a runtime value in a class, you need to make it readonly, then you can set it's value in your constructor, but it cannot be changed after that.



  • Hope_UAE

    The fundamental confusino here is that C++ uses const to mean many different things, from const parameters to const functions to const values. As mentioned, C# only has the notion of a const (compile-time known) value.
     
    You may want to take a look at some interviews with Anders Hejlsberg on the issue:
     
    Search for "Immutables" (match case) in:
     
    Search for "Are you asking why we don’t have read-only parameters also, and const and so forth " in:
     


  • Specfiction

    Thanks.

    I can understand what you mean.

    As you said, I know only C/C++ and was confused to learn C#.

     


  • nick0033

    Hmm... if you don't want to change the reference don't use ref then. There's no other reason to use ref for a parameter other than changing the reference itself. Since you are asking about const I suppose you're a C/C++ programmer. Your example is equivalent to the following C++ code:

    class HogeHoge

    {

    public:

    void UseHoge(Hoge **h) {

    (*h)->someproperty = 1234;

    *h = new Hoge;
    };

     


  • usage of const