Number of copies of instance method and fields? [closed] - c#

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 8 years ago.
Improve this question
Just being curious.
If I create 2 objects of a particular class, then 2 instances of the instance methods and the instance variables are present in the memory for that particular class?
EDIT: I tried with static and for sure, only one instance of the members were there but not sure with instance variables though.

If I create 2 objects of a particular class, then 2 instances of the instance methods and the instance variables are present in the memory for that particular class?
Instance fields - yes. Instance methods (including property accessors), no. Code (both instance and static) is shared among all instances.
Note that static classes will create an additional type for each generic parameter used, and each of those types will share one set of static variables, so for example:
// for example only, not intended to be a perfect singleton implementation
public class Singleton<T> where t : new()
{
private static T _Instance;
public T Instance()
{
return _Instance ?? (_Instance = new T());
}
}
Singleton<Class1> and Singleton<Class2> will each have a different object in memory for _Instance.

Related

What exactly does new object() do in c# [closed]

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 4 years ago.
Improve this question
I have had trouble wrapping my head around this and it seems to have lack luster documentation.
For example, this code:
private static readonly Object obj = new Object();
Can someone parse through this code and explain what is happening here. What exactly are the properties of this new object that was created? Why create an object this way?
You create a new oject with the type of Object. In most cases a statement like this is used for locking purpuse, see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement for more information.
It simply creates an object of a type Object, which is the base type for all of C# reference types.
I has 4 methods:
ToString()
GetHashCode()
GetType()
Equals()
Every class derives form Object, so it has all of the methods above.
Moreover, 3 of these methods are virtual (so you can override them):
ToString()
GetHashCode()
Equals()
It's sometimes used for locking as Isitar mentioned in his answer.
Object obj
that declares a variable of type Object
= new Object();
the equals sign is assignment, the new operator creates a reference to a new instance of class Object and the portion of Object() default initializes it.
it will have the default properties of an object.

Making an object public static vs passing it around [closed]

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 5 years ago.
Improve this question
I am writing a game in Monogame framework and well
there are some objects that have only 1 instance
(but that does not necessarily mean that there should be only 1
instance) during the lifespan of an application by default,
like for example ContentManager.
Now what's bugging me is that I am not sure what is a better practice and why:
To make that object public static and access it from other classes
to use that static instance to load stuff
or
Pass that object as an argument to other classes constructor and use it that way
Just to add another option, you can use the singleton pattern to restrict the creation of new classes, like a GameManager. This pattern comes with cons and pros, so you need to analyze your requirements.
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
The simplest way to implement the implement the pattern is to have a class with a private constructor, a static parameter for your instance and a method to return the instance.
https://en.wikipedia.org/wiki/Singleton_pattern

Referring to private singleton property within singleton class [closed]

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 5 years ago.
Improve this question
In the case of the singleton class seen below, what is the proper way to initialize MyList? Do I refer directly to the field MyList (Option 1) or to Instance.MyList (Option 2)? What's best practice here? My gut says go through Instance, but I'm second-guessing myself and cannot find a definitive answer anywhere.
public class Foo
{
private readonly static Lazy<Foo> _instance =
new Lazy<Foo>(() => new Foo());
private List<string> MyList;
public static Foo Instance
{
get { return _instance.Value; }
}
private Foo()
{
MyList = new List<string> {"a","b","c"}; //Option 1
Instance.MyList = new List<string> {"a","b","c"}; //Option 2
}
}
To start with, I would say that either way is fine. That being said, I prefer the option that doesn't use the "Instance" identifier. The concept of the instance really belongs to the code outside of the singleton class. Inside the class, the fact that it is a singleton should be well known. Thus, specifying the Instance identifier is redundant.
The Singleton pattern is for creating types that can only have one instance, but are still treated like instances of a type, rather than being treated as just a type like static types. So if MyList is part of the single instance, then it should be an instance variable on that instance, not a static member of the class.
One of the perks of the Singleton pattern is that it is easier mock for testing and also easier to transition to using multiple instances later, compared to using static members and classes. For these purposes, making MyList an instance member also helps.
If using an instance, you can write MyList or this.MyList within that instance or Instance.MyList from other places. None of these are more correct than any others, it really depends on what you find readable. The important thing is to not mix conventions, which is the worst readability option.

Difference between in class and constructor initialisation [closed]

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 6 years ago.
Improve this question
I want to understand in the code below
class x
{
int a=3;
...
other class members
}
class y
{
int a;
public y()
{
a=3;
}
...
other class members
}
What is the difference between these two initialisation methods?
Also does it have anything to do with static classes?
Under the C++11 standard, we can supply an in-class initializer for a
data member. When we create objects, the in-class initializers will be
used to initialize the data members. Members without an initializer
are default initialized.
Your first example uses an in-class initializer, while your second example only initializes a within the default constructor.
Say you have another constructor z, which takes some parameters but does not initialize data member a. Then upon calling z,
If you use in-class initializer, it will be used to set a = 3.
If you only initialize a in your default constructor, then a will be uninitialized.

Real life usage of Singleton and Static class c# [closed]

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 8 years ago.
Improve this question
i do not want to know the difference between singleton and static class first of all.
i like to know when people should use singleton class and when static class.
in my apps i use static class for helper or utility method and use singleton for db connection and error logger class. but with the help of static class can be used to return sql db connection object and as well as error logging system.
i really like to know about other senior developer where they use singleton class and where they use static class.
it will very helpful if some one discuss this matter with sample situation and sample code. thanks
If you are creating loosely coupled system, then there is no way you can use static classes (because they cannot implement abstraction and cannot be injected). Static classes also very hard to mock, so it's not your choice if you are doing TDD or simple unit-testing. So, I use them only for dependencies which are not related to business requirements and should not be mocked. E.g. infrastructure logic like logging or mapping.
I also use static classes for extension methods if I cannot extend existing class, but want handy member-like API. Usually this is a also infrastructure-related extensions, like mapping, or serialization, which do not contain business logic.
A very broad question but will give you the first reason that popped into my head for use of a Singleton.
A Singleton is more appropriate than a dedicated static class when you need to manage the lifetime of some cached objects. Singletons are perfect when you want to refresh state without having to worry about thread safety, for example if you have a class that is being used as a singleton and it has many cached properties or lists that incoming requests may want access to.
The Refresh() method can simply be setting the current instance to a new instance and not having to refresh individual properties of the class:
private static YourClass instance = new YourClass(); // first instance
public static void Refresh(){
instance = new YourClass(); // creates a new, refreshed instance while not needing to worry about thread safety
}
public static YourClass Instance{
get{
return instance;
}
}
I usually use singleton classes when I am creating a database access object. Where I can have the instance of the object anywhere inside an application.
I usually stay away from static classes, which the exception of an occasional loader class when loading particular assets.

Categories