Are there any differences between the following two approaches (property with backing field and property with default value) for a lazily evaluated property or are they equivalent?
// (1)
public static class Foo
{
private static readonly Lazy<Foo> instance = new Lazy<Foo>();
public static Foo Instance { get; } = instance.Value;
}
// (2)
public static class Foo
{
public static Foo Instance { get; } = new Lazy<Foo>().Value;
}
What I want to achieve is that an instance of Foo is created only when accessing Foo.Instance, not before --- more so, when Foo.Instance is never accessed, no instance should be created ever.
Well, actually, no, they're not different.
But, and this is just an assumption mind you, they're not working either, at least not the way I hope you intended them do.
You see, this syntax:
<property declaration> = <expression>;
Declares an initializer for the property, which will be executed on construction of the owning type.
So this:
private static readonly Lazy<Foo> instance = new Lazy<Foo>();
public static Foo Instance { get; } = instance.Value;
is not lazy at all. It will declare and construct a Lazy<Foo> (although you're probably missing the getter delegate here as well even though this compiles), however when you declare the property you end up with the property evaluating the lazy object upon construction of the owning type and thus it becomes non-lazy.
The second one has the exact same problem, you construct and immediately evaluate the lazy object so it becomes non-lazy.
The correct way, and this can only be achieved in sort of the first syntax form, is to use the property without an initializer, either this:
private static readonly Lazy<Foo> instance = new Lazy<Foo>();
public static Foo Instance
{
get { return instance.Value; }
}
or this:
private static readonly Lazy<Foo> instance = new Lazy<Foo>();
public static Foo Instance
{
get => instance.Value;
}
or probably best, as this:
private static readonly Lazy<Foo> instance = new Lazy<Foo>();
public static Foo Instance => instance.Value;
This will declare a getter body that doesn't execute until you actually read the property.
TL;DR To sum it up, the two examples you gave are not different, but they're both (probably) wrong and you need to change the property declaration to fix it.
Apart from the excellent answer given by Lasse Vågsæther Karlsen, I would like to further speculate and assume that OP is after Singleton implementation. Here is a fully lazy approach.
Approach 1
public sealed class Singleton {
//Private ctor of course :P
private Singleton() {}
// Instance property to access Singleton Instance
public static Singleton Instance { get { return Nested.instance; } }
private class Nested {
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() { }
internal static readonly Singleton instance = new Singleton();
}
}
Approach 2
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
Related
I'm confused about this statement:
ctrlID.Font.Size = FontUnit.Small;
but FontUnit is a struct under System.Web.UI.WebControls
public struct FontUnit
{
...
public static readonly FontUnit Small;
...
}
as a struct is a class, so how can we have a class A that has its self as a object like:
public class A{
public A a;
}
isn't it like creating an endless chain of objects which would require infinite memory?
The property is static, so it's a member of the Type, and not of the object instance. You do not need to construct the Small static property to create a FontUnit object.
Consider this:
public class Foo
{
public static Foo Default {get;}
static Foo()
{
Default = new Foo();
}
}
Default is only constructed once, at an unknown time before it is used.
If it's not static, you can get into the behavior you expected.
public class Foo
{
public Foo Default {get; private set;}
public Foo()
{
Default = new Foo();
}
}
This will cause an overflow, as the property will keep instantiating a new Foo, which will make a new Foo, and so on.
So long as you're careful not to instantiate a type with the same constructor you are currently instantiating a type in there shouldn't be any issue with a type having member of it's own type.
I have an class and one of the class members is static list that keep all my object and i only want to create this list (List<myObject> list = new ...) once.
what is the best way to do it ?
public class MyObject
{
private string _name;
private static List<Capture> _list;
public MyObject(string name)
{
_name = name;
}
public void start()
{
_list.Add(this);
}
}
I would put it in the class's static constructor or instantiate it inline.
public class MyObject
{
private string _name;
// inline
// private static List<Capture> _list = new List<Capture>();
// if via static constructor
private static List<Capture> _list;
static MyObject()
{
_list = new List<Capture>();
}
public MyObject(string name)
{
_name = name;
}
public void start()
{
_list.Add(this);
}
}
MSDN C# Static Constructors for further reading.
To me this is the best way:
public class MyObject
{
private static readonly List<Capture> _list = new List<Capture>();
}
I would use a thread safe Lazy<T> here,
You can use one of the simple constructors whose default behavior is to create a thread-safe Lazy object, so that only one instance of the lazily instantiated object is created no matter how many threads try to access it.
private static Lazy<List<Capture>> _list =
new Lazy<List<Capture>>(() =>
{
//fill your list
return list;
}, true);
You can find a more detailed explanation here (Lazy and the Singleton Design Pattern) or here (http://csharpindepth.com/articles/general/singleton.aspx)
Just initialize it inline. C# guarantees that static objects will only be initialized once before the are accessed.
public class MyObject
{
private string _name;
private static List<Capture> _list = new List<Capture>();
public MyObject(string name)
{
_name = name;
}
public void start()
{
_list.Add(this);
}
}
As all previous responses mentioned all possible approaches like static ctor or static block I have to ponder the purpose.
According to separation of concerns or single responsibility pattern, there should be another class which would contain list of all implementations, not implementation itself even in a static way. Simplest solution is to use factory (not factory method) along with package visible ctor and store those instances in there.
I wonder if there is a mechanism or pattern to allow only one instance of a class in C#. I have heard of the Singleton class, but i don't know how to use it well.
Using singleton, that is a class which only allows a single instance of itself to be created.
public sealed class Singleton
{
public static readonly Singleton instance = new Singleton();
private Singleton() {}
}
The operation of this pattern is simple and could be reduced to the following:
Hide the constructor of the Singleton class, so that clients may not be instantiated.
To declare the Singleton class private member variable containing the reference to the unique instance that we handle.
Provide in class Singleton a function or property that provides access to the one maintained by the Singleton instance.
this can be sample Singletone implementation
public sealed class CSingleTone
{
private static CSingleTone instance;
public int SomeValue{ get; set; }
public static CSingleTone Instance
{
get
{
if (instance == null)
instance = new CSingleTone();
return instance;
}
}
private CSingleTone()
{
}
}
can be used in this way
int r = CSingleTone.Instance.SomeValue;
You need to read our own Jon Skeet's blog (Implementing the Singleton Pattern in C#).
Intent of Singletom Pattern is to "ensure a class has only one instance, and provide a global point of access to it".
Here's how you can do it.
public sealed class Singleton {
private static readonly Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Singleton is not a class, but rather a pattern.
Here is an example:
class Singleton {
private Singleton() {}
static private Singleton GetIt() {
return theOne;
}
static private Singleton theOne = new Singleton();
}
One option is to just declare a static class with only static members. Or you can implement the Singleton pattern by giving the class a private constructor:
public class MySingleton
{
public static readonly MySingleton Instance = new MySingleton();
private MySingleton() { }
// Members ...
}
here is a simple example of singleton class
class Program
{
static void Main()
{
SiteStructure s = SiteStructure.Instance;
}
}
public sealed class SiteStructure
{
static readonly SiteStructure _instance = new SiteStructure();
public static SiteStructure Instance
{
get
{
return _instance;
}
}
SiteStructure()
{
// Initialize.
}
}
here, Readonly allows thread-safety, and that means it can be only allocated once. It has a public static getter. The Instance property is used by callers to get the singleton instance.
Sealed is known to allow the compiler to perform special optimizations during JIT compilation. The final methods above are the private instance constructor and an Initialize method. Private constructors mean the class can only allocate itself.
a basic question popped in my head this morning. Here it is:
Is there any difference between doing this:
public class MyClass
{
private object _myField = new object();
...
}
and doing the following:
public class MyClass
{
private object _myField;
public MyClass()
{
_myField = new object();
}
...
}
Yes, in the first, the field is initialized before the constructor call. In the second, the field is initialized during the constructor call.
Just to demonstrate casperOne's point...
using System;
public abstract class BaseClass
{
public BaseClass()
{
Console.WriteLine("Result for {0}: {1}", GetType(),
CalledByConstructor());
}
protected abstract string CalledByConstructor();
}
public class VariableInitializer : BaseClass
{
private string foo = "foo";
protected override string CalledByConstructor()
{
return foo;
}
}
public class ConstructorInitialization : BaseClass
{
private string foo;
public ConstructorInitialization()
{
foo = "foo";
}
protected override string CalledByConstructor()
{
return foo;
}
}
public class Test
{
static void Main()
{
new VariableInitializer();
new ConstructorInitialization();
}
}
Here the base class constructor calls an abstract method implemented in the child class - this means we get to see the state of the object before its constructor body starts executing. The results are here:
Result for VariableInitializer: foo
Result for ConstructorInitialization:
As you can see, the variable initializer has already executed - but in the case where initialization only occurs in the constructor body, foo still has its default value of null.
Calling virtual methods from constructors is generally a very bad idea for precisely this sort of reason.
To add to casperOne's answer, those are the only two possible approaches to initializing a readonly field. Per MSDN:
When a field declaration includes a
readonly modifier, assignments to the
fields introduced by the declaration
can only occur as part of the
declaration or in a constructor in the
same class.
In contrast, other fields (ie. not marked readonly) can be assigned elsewhere in the class, such as via a method call, although that could lead to needing to check its state before usage.
As far as I know you can can't pass parameters to a static constructor in C#.
However I do have 2 parameters I need to pass and assign them to static fields before I create an instance of a class. How do I go about it?
This may be a call for ... a Factory Method!
class Foo
{
private int bar;
private static Foo _foo;
private Foo() {}
static Foo Create(int initialBar)
{
_foo = new Foo();
_foo.bar = initialBar;
return _foo;
}
private int quux;
public void Fn1() {}
}
You may want to put a check that 'bar' is already initialized (or not) as appropriate.
You can't pass parameters to a static constructor, but you can pass parameters to the class itself - via generic type parameters.
Slightly crazy this idea, however, I'll just throw it out there anyway.
Make the class generic (with a TypeParam that will provide a parameter type) and place generic constraints on it (details in code example), then derive a new parameter type, which contains virtuals that you can use to read what they want the parameter values to be.
//base parameter type - provides the 'anchor' for our generic constraint later,
//as well as a nice, strong-typed access to our param values.
public class StaticParameterBase
{
public abstract string ParameterString{ get; }
public abstract MyComplexType ParameterComplex { get; }
}
//note the use of the new() generic constraint so we know we can confidently create
//an instance of the type.
public class MyType<TParameter> where TParameter:StaticParameterBase, new()
{
//local copies of parameter values. Could also simply cache an instance of
//TParameter and wrap around that.
private static string ParameterString { get; set; }
private static MyComplexType ParameterComplex { get; set; }
static MyType()
{
var myParams = new TParameter();
ParameterString = myParams.ParameterString;
ParameterComplex = myParams.ParameterComplex;
}
}
//e.g, a parameter type could be like this:
public class MyCustomParameterType : StaticParameterBase
{
public override string ParameterString { get { return "Hello crazy world!"; } }
public override MyComplexType { get {
//or wherever this object would actually be obtained from.
return new MyComplexType() { /*initializers etc */ };
}
}
}
//you can also now derive from MyType<>, specialising for your desired parameter type
//so you can hide the generic bit in the future (there will be limits to this one's
//usefulness - especially if new constructors are added to MyType<>, as they will
//have to be mirrored on this type as well).
public class MyType2 : MyType<MyCustomParameterType> { }
//then you'd use the type like this:
public static void main()
{
var instance = new MyType<MyCustomParameterType>();
//or this:
var instance2 = new MyType2();
}
I did consider a solution that employs custom type attributes applies to a type parameter, however this is easily a better way. However, you'll now be using your class always with a generic parameter type (unless you can use the deriving+specialisation trick) - possibly too clumsy for your liking.
I'd also prefer this over the other solutions presented here as it doesn't require creating any workarounds for the static initialisation - you can still use .Net's guarantee of single-time initialisation.
A word of warning - should you be reviewing your structure?
All that said - remember, though, since you can only parameterise the static once (or in this case, each uniquely parameterised static generic) - I would be asking myself why not just pull the code that is getting the parameters to give to the static, and place it in the static constructor in the first place? That way you don't actually have to resort to strange patterns like this!
I assume you mean static members of a class? In that case, you can do this:
public class MyClass
{
public static int MyInt = 12;
public static MyOtherClass MyOther = new MyOtherClass();
}
Those static members are guaranteed to be instantiated before any class is instantiated.
If you need complex logic, do it in a static constructor:
public class MyClass
{
public static int MyInt;
public static MyOtherClass MyOther;
static MyClass()
{
MyInt = 12;
MyOther = new MyOtherClass();
}
}
Edit
Based on your edit, I'd say just assign the values to what they need to be before you instantiate the class, like so:
public class MyClass
{
public static int MyInt;
public static MyOtherClass MyOther;
}
// elsewhere in code, before you instantiate MyClass:
MyClass.MyInt = 12;
MyClass.MyOther = new MyOtherClass();
MyClass myClass = new MyClass();
That said, this method gives you no guarantee that MyInt and MyOther are set before MyClass is instantiated. It will work, but requires discipline before instantiating MyClass.
One alternative pattern you might follow looks like this:
public class MyClass
{
private static int MyInt;
private static MyOtherClass MyOther;
private static bool IsStaticInitialized = false;
public static InitializeStatic(int myInt, MyOtherClass other)
{
MyInt = myInt;
MyOther = other;
IsStaticInitialized = true;
}
public MyClass()
{
if(!IsStaticInitialized)
{
throw new InvalidOperationException("Static Not Initialized");
}
// other constructor logic here.
}
}
// elsewhere in your code:
MyClass.InitializeStatic(12, new MyOtherClass());
MyClass myClass = new MyClass();
// alternatiavely:
MyClass myClass = new MyClass(); // runtime exception.