Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method you can only run in a constructor [duplicate]

Tags:

c#

constructor

Is there a way to mark a method in c# so it can only run in the constructor? Basically, I have a load of read only string arrays that I need to update with the base columns in the constructor so I do the following:

    public CMSBlogContext(ICMSRelationshipContext relationshipContext)
    {
        _relationshipContext = relationshipContext;
        ColumnNames.AddBaseColumns(ref _blogAuthorColumns);
        ColumnNames.AddBaseColumns(ref _blogCardColumns);
        ColumnNames.AddBaseColumns(ref _blogCategoryColumns);
        ColumnNames.AddBaseColumns(ref _blogPageColumns);
        ColumnNames.AddBaseColumns(ref _blogPostColumns);
    }

I thought I could tidy this up by moving the columns into a separate function like so:

    public CMSBlogContext(ICMSRelationshipContext relationshipContext)
    {
        _relationshipContext = relationshipContext;
        AddBaseColumns();
    }

    private void AddBaseColumns() 
    {
        ColumnNames.AddBaseColumns(ref _blogAuthorColumns);
        ColumnNames.AddBaseColumns(ref _blogCardColumns);
        ColumnNames.AddBaseColumns(ref _blogCategoryColumns);
        ColumnNames.AddBaseColumns(ref _blogPageColumns);
        ColumnNames.AddBaseColumns(ref _blogPostColumns);
    }

But obviously this complained that read only can only be updated in the constructor, so is there a way to make a method only able to run in the constructor (or rather, is there a way to put those read only updates into a method not in the constructor but will only run in the constructor)?

like image 916
Pete Avatar asked Sep 07 '25 07:09

Pete


1 Answers

One thing you could do is to use a base class and put the properties on that. Then you could use the base class' constructor to set up the read only fields like so:

  public class Test:TestBase {

    public Test(): base() { 

    }

    public string GetExample() { 
     return example;
    }

}

    public class TestBase {
    protected readonly string example = "";

     public TestBase() { 
      example ="hi";
    }

}

I can now use this like so and it works:

var test = new Test();
Console.WriteLine(test.GetExample());

That way you hide away the fields but also enforce the constructor only accessiblity of read only fields.

like image 90
K-Dawg Avatar answered Sep 10 '25 03:09

K-Dawg