Is it possible to simplify the following into one row? [duplicate] - c#

This question already has answers here:
static property in c# 6
(3 answers)
Closed 4 years ago.
I apologize for a really bad title. I don't know the correct terminology, but will edit it if you can inform me what I am actually asking.
Is it possible to do the following in one row, like with an auto-property?:
public class MyClass
{
static OtherClass _otherClass;
static OtherClass otherClass => _otherClass ?? (_otherClass = new OtherClass());
}

You could use Lazy<T> for lazy initialization, although it does not simplify the code too much:
static Lazy<OtherClass> _otherClassLazy = new Lazy<OtherClass>(() => new OtherClass());
static OtherClass otherClass => _otherClassLazy.Value;
Lazy<T> initializes the value only once, and only when actually accessed.
If you really want a single line, you can use:
static Lazy<OtherClass> otherClass { get; } = new Lazy<OtherClass>(() => new OtherClass());
At the cost of having to use otherClass.Value when referring to this variable in code.
This solution is preferable to the { get; } = new OtherClass() in case you want to initialize the property only on-demand, not during the initialization of the class itself. This may be desirable in case the constructor is doing a lot of work and the property might not be used in some cases.

Related

C# get the name of a method that called another one [duplicate]

This question already has answers here:
How can I find the method that called the current method?
(17 answers)
How do I get the calling method name and type using reflection? [duplicate]
(5 answers)
Get the calling function name from the called function [duplicate]
(2 answers)
How to find the FULL name of the calling method in C#
(5 answers)
Closed 1 year ago.
Here is my problem: I have two classes which each include a method. Method 1 of class 1 calls method 2 of class 2.
Now, I need to store in a local variable of method 2 (of type string probably), the name of the method that called method 2 (i.e. Method1).
For this I have set up a global variable named string str in class 2. However, as we create a new instance of class 2 when we call method 2, we have: str=null.
Here is the code so that you understand the problem:
public class Class1
{
private Class2 _class2 = new Class2();
public Class2 Class2 { get => _class2; set => _class2 = value; }
public void Method1()
{
Class2.data = "Changes I want to Make in Class2";
Class2.Method2();
}
}
public class Class2
{
public string data;
public void Method2()
{
string str = data; //str=null instead of str="Changes I want to Make in Class2"
//Rest of the code here
}
}
I know that str=null since I instantiate the object Class2 = new Class2().
So, I need to find another way around the problem, and I realised that, in my case, getting the name of Method 1 from a local variable in Method 2 would be a solution.
My question is therefore the following: Is there a way to answer this problem?
Note: I am a beginner in computer development, so I apologise in advance if the solution is easy and I have not seen it before.

Why does it compile? Assigning to a read only property works fine [duplicate]

This question already has an answer here:
Why can I use initializer syntax with readonly properties [duplicate]
(1 answer)
Closed 3 years ago.
I came over a weird behavior of C# compiler. Can you elaborate why this code just works fine?
public class A
{
public void Test()
{
var x = new B
{
// assigning to a read only property
ReadOnlyProperty = {new KeyValuePair<int, int>(1, 1)}
};
}
}
class B
{
public IDictionary<int,int> ReadOnlyProperty { get; }
}
The expected behavior is not being able to assign anything to readonly properties.
This is not an assignment, it's a collection initializer. The statement in your ctor is equivalent to the following code:
var x = new B();
x.ReadOnlyProperty.Add(new KeyValuePair<int, int>(1, 1));
Thus, you're only getting the property (and manipulating the instance), not setting it. Keep in mind that readonly does not prevent you from changing the state of an object; only that you cannot assign to that field outside the ctor and its initializer.

What's the order of initialization? [duplicate]

This question already has answers here:
Initialization Order of Static Fields in Static Class
(3 answers)
Closed 4 years ago.
Will it always works correctly?
public class Test
{
public static List<int> a = new List<int>{1,2,3};
public static List<int> b = new List<int>(a);
}
Because when I switched them
public class Test
{
public static List<int> b = new List<int>(a);
public static List<int> a = new List<int>{1,2,3};
}
then I received
Exception in user code:
System.ArgumentNullException: Value cannot be null.
Parameter name: collection
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at .Test..cctor()
Are there any other things I have to worry about?
If you need deterministic initialization, use a static constructor:
public static List<int> a;
public static List<int> b;
private static Test()
{
a = new List<int>{1,2,3};
b = new List<int>(a);
}
The C#/CLR specification ensures the order in which field initializers are executed, but as you've noticed, if you mess up the ordering of your fields in the class, things break down at runtime. That's a bad idea regardless of the contractual behavior, given how easy it is to switch the order of fields in a class.
So my advice is: if the field initializers don't depend on other fields, keep them. If they do, put the initialization in a constructor, where the ordering is very explicit.
The relevant quote from specification:
If a class contains any static fields with initializers, those initializers are executed in textual order immediately prior to executing the static constructor (ยง17.4.5).
So you can rely on the textual order contractually, but I'd still recommend against it. It's way too easy to break, and people usually don't consider the order of members in the code file of a class important. It would be fine if you got a compilation error, but you don't - if you're lucky, you get a runtime error. If you're not, you're going to be scratching your head with "impossible" situations that had nothing to do with your changes (right?).
Yes as you have observed correctly the order has to remain as below since the member fields will get initialized in accordance order
public static List<int> a = new List<int>{1,2,3};
public static List<int> b = new List<int>(a);

Instantiate a class to call a method or use static methods? [duplicate]

This question already has answers here:
C# static vs instance methods
(8 answers)
Closed 6 years ago.
Let's say I have a class
public class product
{
public string GetName()
{
return "product";
}
public static string GetStaticName()
{
return "product";
}
}
These methods do the same thing but one is static and one isn't.
When i call these method I do this:
product p = new product();
string _ProductName = p.GetName();
and
string _ProductName = product.GetStaticName();
Which method is the best to use for performance etc?
Which method is the best to use for performance etc?
You haven't to address any performance issue here. You just have to decide if this method should be the same for all the instances of the objects you create. If the answer is yes, then it should be a static method. Otherwise, it should be an instance method. It's a design decision, not a performance decision.
By the way, based on your code. I don't think that in this case you have to address even that. You just want to get the name of the product and probably set it. That being said the following is the only thing you need.
public class Product
{
public string Name { get; set; }
}

Creating data members of a class 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 8 years ago.
Improve this question
I am a beginner programmer looking for some help with c#.
I am writing a program based on a framework and need to create a data member of a class, then initialize the data member to something.
Next,I need to make a property to get and set the data member.
Also, if someone could provide some information on how to typecast the property that would be great.
I'm just looking for examples and general information here. I checked google and only got links from MSDN but did not understand the content.
Thanks!
Here is a basic explanation, using code:
//Class Definition
public class MyClass
{
//Data Member with inline initialization
private int myInt = 1;
//Standard property
public int MyIntProp
{
get { return myInt; }
set { myInt = value; }
}
//Auto-property, generates the same getter/setter as above with a "hidden" backing property.
public String MyStringProp {get; set;}
//Class constructor, great for initialization!
public MyClass()
{
//Set the property to an initial value
MyStringProp = "Hello World";
}
}
Typecasting is another monster. You have to be careful when doing it, because very few types can be cast to others. The number types can generally be cast to one another (although you can lose data), and derived types can be cast to their base types, but that is about it.
An example (safe) cast of a number would be:
int myInt = 2;
long myLong = (long)myInt;
That is called a "C-Style" cast (because it's how you do it in C) and is generally how you cast numbers. There are other styles and functions to do the cast of course.
#Iahsrah's suggestion is also a good place to start.
A basic type is a class which looks like this:
public class MyType
{
}
You can create a property of this on another class like this:
public class AnotherType
{
public MyType InlinePropertyName { get; set; }
// Simple propertoes require no implimentation (above), or you can explicitly control it all (below)
private MyType _explicitPropertyName;
public MyType ExplicitPropertyName {
get {
return _explicitPropertyName;
}
set {
_explicitPropertyName = value;
}
}
}
The you can easily access from elsewhere in your program like this:
var myType = new MyType();
var anotherType = new AnotherType();
anotherType.InlinePropertyName = myType;

Categories