Is it possible to make 3 stacks of locations? Stack<>() - c#

Is it possible to do a stack like this
Stack<Location> labels = new Stack<Location>()
labels.Push(label1, 400, 100)
labels.Push(label2, 400, 200)
I need to know if this is possible. If it is please tell. Thanks

Yes, although I wouldn't advice it. Create an extension method and place it into a public static class. The following example assumes that there's a constructor accepting a string and two integers for the class Location.
public static class ExtensionMethods
{
public static void Push(this Stack<Location> stack, string label, int x, int y)
{
stack.Push(new Location(label, x, y));
}
}

For that matter,
You can also also create a LocationStack class which wraps your Stack<Location>, and exposes the friendly method that you are looking for!!

Related

Judge whether a property is created by a function via reflection

Suppose I have a class Foo like below:
class Foo
{
public static int Bar()
{
return 1;
}
public static int x = Bar();
public static int y = 2;
}
I want to use reflection to know that:
x is initialized via the function Bar.
y isn't initialized via the function Bar.
Is there any way to do this?
Sorry but none of your properties are created from your function Bar anyway.Are you talking about initialization and or when/where are they assigned?
Please clarify your question.
A similar question was asked here: When do static variables get initialized in C#?
EDIT
Based on the new information you can change Access Modifiers or utilize the [Obsolete] attribute: https://learn.microsoft.com/en-us/dotnet/api/system.obsoleteattribute?view=netframework-4.7.2
to control or restrict creation.

How to dynamically decide which static class to use

We have a large class that contains a bunch of css selectors stored as static strings. Example:
public class Constants
}
public static string Selector1 = "#someID";
public static string Selector2 = ".some.classes a";
// and so on...
}
We now need to test a different version of our web app which requires a few different selectors. So we need to find a clean scalable way to override these selectors based on some configuration.
My solution to the problem is this: I'm trying to create a BaseConstants class which will have the current set of selectors. Then I create another class called UpdatedConstants which will subclass the BaseConstants class. This class will then contian all the selectors and just override the ones that need changing with the new keyword. Example:
public class UpdatedConstants : BaseConstants
{
// Overrides the base class's Selector1 string
public new static string Selector1 = "#someOtherID";
}
This works well for overriding the strings however I'm stumped as to how the project will decide which static class to use when it is compiled. All our existing code uses the Constants class like this:
var element = driver.GetElement(Constants.SomeSelector);
Is there a way to dynamically decide which class is the final Constants class? Perhaps by some meta-programming magic?
Let me know if anyone has questions or needs a better explanation of the problem. Thanks
Make your constants classes non-static and use a singleton. This also lets you use virtual properties, since you want to use a base Constants class.
public static class Constants
{
static Constants()
{
#if FOO
Current = new ConstantsFoo();
#elif BAR
Current = new ConstantsBar();
#endif
}
public static ConstantsBase Current { get; private set; }
}
//...snip
var element = driver.GetElement(Constants.Current.SomeSelector);
If you don't want to change all occurences Constants.SomeSelector, the only way to have different behavoirs is using pre-processor directives in the Constants class:
public class Constants
}
#if OLD
public static string Selector1 = "#someID";
#elif NEW
public static string Selector1 = "#someNewID";
#endif
public static string Selector2 = ".some.classes a";
// and so on...
}
Else you can use the approach from Ed Plunketts answer.
Okay, probably not what you're looking for, but... You might want to consider not doing it like this.
Put it this way - if you travel down the road, what will your code look like in 5 years? You'll have a base class that contains your original settings, a subclass for how they were modified the first time (when you asked this question), a subclass inheriting from that subclass on how they were modified the next time, and so on. I could easily imagine 10 subclasses in a giant chain - and if you wanted to trace the current value for any setting, you'd have to travel up that chain until you found where it was most recently set/overriden. It sounds like a maintenance nightmare, to be honest.
If I were in your shoes, this is what the new code would look like:
public static class Constants
{
public static string Selector1 { get { return ReadFromSettings("Selector1"); } }
public static string Selector2 { get { return ReadFromSettings("Selector2"); } }
//etc
// then, code for ReadFromSettings()
}
... and then migrate those settings into an actual settings file. Nobody needs to change any code on the calling end (they still reference Constants.Selector1) - except, instead of having this all hard-coded in a series of derived classes, you just have a file with your values.

Method overloading or something more elegant? [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 6 years ago.
Improve this question
I am writting some code in C# and I noticed scenario like below. I wonder how can I make this more elegant and easy to maintain.
If I have following scenario with overloads
public void DoSmtg(string a) { DoSmtg(a, 0, 0f); }
public void DoSmtg(string a, int x) { DoSmtg(a, x, 0f); }
public void DoSmtg(string a, int x, double d) { // method logic }
say now I need to add another bool parameter. I would have to modify this to
public void DoSmtg(string a) { DoSmtg(a, 0, 0f, false); }
public void DoSmtg(string a, int x) { DoSmtg(a, x, 0f, false); }
public void DoSmtg(string a, int x, double d, bool doIt) { // method logic }
This is a very simple example. It is possible to have say 10 more versions of DoSmtg() method. Clearly, this code smells. While overloading is quite valid, it obviously makes it hard to maintain this code since:
there are many methods to be written
it is not obvious which method is called until careful investigation (especially if method has more parameters)
method gets poluted by growing parameter list
the new parameter added requires changes at many places (think about the methods above called from many different locations)
What would be an elegant, simple and good way to avoid something like this?
You could try adding all the parameters on one function, using default values and name the parameters when you call the function:
public void DoSmtg(string a, int x=0, double d=0f, bool doIt=false) {
// method logic
}
When calling the function, you would then do:
DoSmtg("yo!")
DoSmtg("yo!", d:0.59, doIt:true)
You could wrap all the parameters up in a POCO:
public class SomethingParameters
{
public string A { get; set; }
public int X { get; set; }
public double D { get; set; }
public bool DoIt { get; set; }
}
Then the method signature becomes:
public void DoSmtg(SomethingParameters parameters) { // method logic }
I like this pattern because it's easy to extend in the future. If you need to add five more parameters, or optional parameters, no problem!
You can call it like:
var parameters = new SomethingParameters()
{
A = "foobar",
X = 123,
D = 0.123,
DoIt = false
}
DoSmtg(parameters);
If you have a lot of code calling the old method signature that you don't want to break, you could keep your existing overloads but have them call the new one:
public void DoSmtg(string a, int x, double d, bool doIt)
=> DoSmtg(new SomethingParameters()
{
A = a,
X = x,
D = d,
DoIt = doIt
});
I prefer the option of using a separate class for parameters. But perhaps, as you said, you're already calling the method in multiple places and don't want to modify it.
In that case you can add an optional parameter:
public void DoSmtg(string a, int x, double d, bool doIt = false)
Nothing has to change anywhere else except that you can supply the parameter if you choose to.
If you find yourself doing this I'd still write the extra overload using a class anyway and start using that. Optional parameters can start to get messy too if there are too many of them.

With a struct that is a property, what is the standard for updating a value in the struct?

I'm new to C#, and I'm working with a class that has a Rectangle field. I've read that Properties are the most accepted way to declare public fields, so I tried something like this:
public class MyClass
{
public Rectangle MyBox { get; set; }
public UpdateBox(int x, int y)
{
MyBox.X = x;
MyBox.Y = y;
}
}
It won't let me do MyBox.X = x because (from what I've read), Rectangle is a struct, and the getter returns a copy of the Rectangle, so I would not be modifying the value I want.
What is the standard for updating fields like this? I've found two solutions so far:
Creating a new Rectangle to store in the variable:
public class MyClass
{
public Rectangle MyBox { get; set; }
public UpdateBox(int x, int y)
{
MyBox = new Rectangle(x, y, MyBox.Width, MyBox.Height);
}
}
but this seems like it would not be very memory efficient. Then there is just not making Rectangle a property:
public class MyClass
{
public Rectangle MyBox;
public UpdateBox(int x, int y)
{
MyBox.X = x;
MyBox.Y = y;
}
}
What is the standard for this kind of functionality?
By convention you can use a struct as a field and access its internal fields directly, if you want to use it as a property, then make a proper setter for it.
I, personally only use struct types as fields other than properties, maybe a read only property for public access (for encapsulation purposes), grants me safety and general organization of my code.
Your 3rd block of example code is the most correct form in my view, and no its not memory inefficient, Rectangle MyBox is already allocated in memory and already consuming its most by the time the constructor is called.
Also, let us keep in mind here, a property is a "shortcut" function to access some data, but if this data ought to be stored somewhere and wont likely change (default get/set accessors), then it's not any different from a normal field.
This is my favorite way of dealing with this:
public class MyClass
{
private Rectangle _MyBox; // or protected idk.
// This is public and read only.
public Rectangle MyBox { get { return _MyBox; } }
public UpdateBox(int x, int y)
{
_MyBox.X = x;
_MyBox.Y = y;
}
}
The clearest approach for non-speed-critical applications is to use the pattern:
var temp=myThing.TheProperty;
temp.X = whatever;
temp.Y = whatever;
myThing.TheProperty = temp;
If the structure behaves as a bunch of independent variables fastened together with duct tape, the above approach will avoid having to either have the client code know about all of its fields, or have the struct include lots of boilerplate WithX, WithY, etc. factory methods.
If speed is important, then one should either have structures exposed in fields or arrays [as opposed to other collection types], or--if one wants to retain encapsulation--include accessor methods:
delegate void ActionRR<T1,T2>(ref T1 p1, ref T2 p2);
void ActOnBounds<TExtra>(ref Rectangle bounds, ActionRR<Rectangle, TExtra>proc, ref TExtra extra)
{
proc(ref _bounds, ref extra);
}
Note that generating delegates to call ActOnBounds will make it slow, but it may be used efficiently by passing a static delegate and a ref valuetype. Unfortunately, while C# includes lots of nice syntactic sugar for closures, it does not provide such help with constructs like the above.

Extending string with Extension Methods (C# 3.0)?

I know I can extend the string class like so:
public static class EMClass
{
public static int ToInt32Ext(this string s)
{
return Int32.Parse(s);
}
public static int ToInt32Static(string s)
{
return Int32.Parse(s);
}
}
And use it like this:
string x = "12";
x.ToInt32Ext()
But how can I make it to where I can use it like this:
int x = string.ToInt32("15");
I don't think you can do "static" extension methods.
Dude, do you have any problems with Int32.Parse() ?
What I did in our project at work is created a class called Strings which is where I put all of our extension methods. That way you have something that visually looks similar to string.
You can call the extension method in your example like so too (not all people might like this, but I use this myself depending on the code I'm working on):
int x = "15".ToInt32();
Extension methods only apply to instances of a class, not the class itself. You can't extend a class with a class method using an extension. Note that you should easily be able to do what you want with an extension method, just using.
var fifteen = "15".ToInt32Ext();
You can't really do this... the closest you are going to get is this:
public static class Ext
{
public static class String
{
public static int ToInt32(string val)
{
return Int32.Parse(val);
}
}
}
//Then call:
Ext.String.ToInt32("32");
Which i'm surprised the compiler even allows you to name a class "String"
Just for entertainment, i thought of another fun way to do it, though i would never recommend this. Add:
using String = NameSpace1.Ext.String;
//Then you can access it as:
String.ToInt32("32"); //Yipes
Personally, I don't see a lot of use for an extension-method wrapper to a method call that's already a short one-liner. On the other hand, wrapping the Int32.TryParse pattern to return a nullable int can be pretty convenient:
public static int? ToInt32(this string input)
{
if (String.IsNullOrEmpty(input))
return null;
int parsed;
if (Int32.TryParse(input, out parsed))
return parsed;
return null;
}
This allows you to parse a value that might not be present, or might not contain an integer, and provide a default value in a single line of code:
int id = Request.QueryString["id"].ToInt32() ?? 0;

Categories

Resources