C
C#17mo ago
MrScautHD

❔ QUESTION Static GETER

Would this everytime i call it create a new ContentBuilder? or just one time
public static ContentBuilder ContentBuilder => new("content");
public static ContentBuilder ContentBuilder => new("content");
15 Replies
Pobiega
Pobiega17mo ago
every time.
MrScautHD
MrScautHD17mo ago
ouf is it possible to just do it 1 time?
Pobiega
Pobiega17mo ago
sure, declare a static instance and return that or make a singleton of sorts
MrScautHD
MrScautHD17mo ago
public static readonly ContentBuilder ContentBuilder = new("content");
public static readonly ContentBuilder ContentBuilder = new("content");
and that would create to everytime a new one? in one line not possible?
Pobiega
Pobiega17mo ago
private static ContentBuilder _content = new("hello");
public static ContentBuilder ContentBuilder => _content;
private static ContentBuilder _content = new("hello");
public static ContentBuilder ContentBuilder => _content;
hm, not with a getter or actually, maybe
MrScautHD
MrScautHD17mo ago
i mean if i set it just readonly it do the same ?
Pobiega
Pobiega17mo ago
public static ContentBuilder ContentBuilder { get; } = new("content"); that should work
MrScautHD
MrScautHD17mo ago
👍
Pobiega
Pobiega17mo ago
readonly would give you a similar development experience, yes
MrScautHD
MrScautHD17mo ago
and it get not created everytime i call it or?
Pobiega
Pobiega17mo ago
nope. just the once
MrScautHD
MrScautHD17mo ago
👍 thx for your help
Pobiega
Pobiega17mo ago
just to visualize this..
public static class Program
{
public static ContentBuilder Once { get; } = new("once");
public static ContentBuilder Many => new ContentBuilder("many");
public static void Main()
{
Once.Content.ToLower();
Once.Content.ToLower();
Once.Content.ToLower();
Many.Content.ToLower();
Many.Content.ToLower();
Many.Content.ToLower();
}
}

public class ContentBuilder
{
public ContentBuilder(string content)
{
Content = content;
Console.WriteLine(content);
}

public string Content { get; set; }
}
public static class Program
{
public static ContentBuilder Once { get; } = new("once");
public static ContentBuilder Many => new ContentBuilder("many");
public static void Main()
{
Once.Content.ToLower();
Once.Content.ToLower();
Once.Content.ToLower();
Many.Content.ToLower();
Many.Content.ToLower();
Many.Content.ToLower();
}
}

public class ContentBuilder
{
public ContentBuilder(string content)
{
Content = content;
Console.WriteLine(content);
}

public string Content { get; set; }
}
this will print "once" once and "many" three times
MrScautHD
MrScautHD17mo ago
👍
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.