Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
For example, I have an Profile class with profile settings and want to provide several default profiles with according settings. What is the best way to do it?
I know some classes in .NET that have such functionality - like String with its static String.Empty property.
1. My current approach is
public static readonly ICollection<Profile> DefaultProfiles;
field inside Profile class. This field is filled with default profiles inside Profile's static constructor.
2. The bad case for this approach is serialization - serialization requires not static, not readonly members. So to serialize my Profile with default profiles I have to create special not static, not readonly property for it. But I also want the entities of Profile class have no new individual default profile list before serialization (of course it can't be after it). Can I reach it like this?
[Serializable]
public class Profile
{
public static readonly ICollection<Profile> DefaultProfiles;
public List<Profile> DefaultProfilesToSerialize
{
get { return new List<Profile>(DefaultProfiles);; }
}
}
So without any backing field for DefaultProfilesToSerialize there is only one instance of default profiles for each instance of Profile. Am I right?
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have read something's, about static classes, mostly about that static classes are "evil" in Java, and I was wondering what does the Static calss actually do?
What are the applications to it Unity C#, and C# in general?
"The static modifier makes an item non-instantiable, it means the static item cannot be instantiated. If the static modifier is applied to a class then that class cannot be instantiated using the new keyword. If the static modifier is applied to a variable, method or property of class then they can be accessed without creating an object of the class, just use className.propertyName, className.methodName."
Static class basically means that there is just one instance of the object.
It can be good or bad, depends on what you need, for example if you have an int to store the player money you can use static int money and then get or set the variable
from anywhere, but if you want to create something multiple time (like enemies etc') you cann't use it.
Here is a link to read more about the Static class
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
We have a small disagreement within my team over whether injected dependencies should be stored as readonly fields:
public class MyClient
{
private readonly IService service;
public MyClient(IService service)
{
this.service = service;
}
}
or as private readonly properties:
public class MyClient
{
private IService Service { get; }
public MyClient(IService service)
{
Service = service;
}
}
Are there any advantages to one choice over the other? I favour the former but it seems half of our classes use the latter.
You should use a readonly field.
The are three reasons to use properties over fields:
You want to add some extra logic which is run when the property is accessed.
You want to reserve the right to add some extra logic in the future, without changing your interface.
You're using some tool / serialization framework which only deals with properties, and ignores fields.
Point 2 is why people recommend using properties instead of fields for all public (and sometimes protected) members. Point 1 (and perhaps point 3, in rare cases) is the only reason you would create a private property.
None of those points apply here. The property is only adding extra overhead, and there's no reason to pay that cost for zero gain.
I think readonly field is the safest approach as it prevents you from creating a new instance of the field in a different place than the constructor(Single Responsibility Principle). The decision what kind of implementation for interfaces should be used in a given class should be done at the level of the DI container. You can inject different objects for different environments, based on the app settings in your Continuous Delivery pipeline. Though you don't have to worry about weird things like e.g. using some AzureSerive when using OnPremise version of the app etc.
[Using a private readonly property with a getter or a private readonly field is equivalent in term of generated bytecode, so it's just a matter of taste.] <-- this is not true, as pointed below. Sorry for the inconvenience.
I prefer (and use) private fields, as I consider them more clear semantically (in my mind a field is private, fullstop) and less verbose (no need for that awful { get; }, I hate getters 😄).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
It seemed like this was possible, but I can't find a reference on how to accomplish it, though I've seen a few things that are closely related. I have a particular type of class that requires a public or private default ctor. The reason is stylistic; it is a domain aggregate and the only case where a default ctor should be used is during event store replay. There are obvious ways to work around this, but I'm trying to lock this particular type down. At any rate, what I'm hoping to do is create an attribute that can be applied at the class level that would enforce the existence of a default ctor. If one isn't found, it won't compile... or at the very least, give it the big nasty blue underline like [Obsolete()] does. I figured this was potentially doable with Roslyn. Any direction would help. The solution would ideally travel with the project rather than being something that needs to be installed on visual studio.
Just a simple idea, for a public default constructor you could make use of the where T : new() constraint - even though attributes cannot be generic you can supply typeof(HasDefaultConstructor<MyClass>) as an argument to an attribute:
public static class HasDefaultConstructor<T> where T : new() { }
public class CheckAttribute : Attribute
{
public CheckAttribute(Type type) { }
}
[Check(typeof(HasDefaultConstructor<MyClass>))]
public class MyClass
{
public MyClass() { }
}
But it feels a bit hacky having to supply the type you're applying the attribute to, and doesn't work for the non-public constructors, but it does fail at compile-time without needing any addons.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a class with only static methods. Should the class itself be made static too? Does it matter?
Does it matter?
Making a class static ensures that it can never be instantiated by generating a compiler error should the user attempt to do so. If the class, consisting of only static members, is simply not intended to be instantiated, there is no reason not to make it static. You can choose not to do so, but instances of such a class aren't going to be very useful, and users creating these instances are going to be left quite confused.
On the other hand, if you intend for instances of this class to be created but you expect derived classes to implement their own instance members, chances are that this class should be abstract, rather than static (and perhaps those instance members should be stated upfront via abstract definitions or an interface).
In general: Yes.
You can prevent the programmer to create object instances of a certain class by making the class static. If this is what you intend, then do it. This prevents mistakes, by showing (other collegues, etc.) that the class is not intended to be instantiated.
public static class A
{
// Some static member
}
A a = new A(); // Compilation error
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Recently I am working a server that transfers commands and data and in my global variables, I have a 100 constants that I use through out my program for communication protocols. Is there a way I can make a class of global variables and then access that class when needed?
One way would be to create a class and mark it as static:
public static class GlobalVariables
{
public static int GlobalInt;
public static float GlobalFloat;
}
You'll be able to access these anywhere in your program.
If you do not want anyone to be able to edit these values, you could mark them with the const keyword:
public const int GlobalInt = 15;
Create a static class and mark your fields with const keyword, it's implicitly static and you won't be able to overwrite them by accident.
In addition to the suggestions above, is there any chance that these "constants" might change in the future? The reason I ask is that you mentioned they were communication protocols. If its things like addresses, ports or anything else that might change, consider using the static class and on that class use a static constructor to read the values from the configuration or have the static properties of that class just refer to the configuration. You don't want a firewall change to force you to have to recompile your code.
If a value has no chance of changing, it should be a const.