C
C#2y 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
Pobiega2y ago
every time.
MrScautHD
MrScautHDOP2y ago
ouf is it possible to just do it 1 time?
Pobiega
Pobiega2y ago
sure, declare a static instance and return that or make a singleton of sorts
MrScautHD
MrScautHDOP2y 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
Pobiega2y 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
MrScautHDOP2y ago
i mean if i set it just readonly it do the same ?
Pobiega
Pobiega2y ago
public static ContentBuilder ContentBuilder { get; } = new("content"); that should work
MrScautHD
MrScautHDOP2y ago
👍
Pobiega
Pobiega2y ago
readonly would give you a similar development experience, yes
MrScautHD
MrScautHDOP2y ago
and it get not created everytime i call it or?
Pobiega
Pobiega2y ago
nope. just the once
MrScautHD
MrScautHDOP2y ago
👍 thx for your help
Pobiega
Pobiega2y 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
MrScautHDOP2y ago
👍
Accord
Accord2y 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.
Want results from more Discord servers?
Add your server