Question

I currently have some global variables like this (the global part isn't really relevant):

public Brush backgroundColor;
public Brush textColor;
public double timeOffset;
public double dateOffset;
public string title;
public bool showTitle;
public bool showText;

I declare a new List<string> to store said variables using this:

List<string> x = new List<string>();
x.Add(backgroundColor);
x.Add(textColor);
x.Add(timeOffset.ToString());
x.Add(dateOffset.ToString());
x.Add(title);
x.Add(showTitle.ToString());
x.Add(showText.ToString());

Noticeably, I'm only temporarily storing these strings into my list. I will be using them later on as objects. If I wanted to convert my strings from this list to types like bool or double, I can simply us Convert.ToDouble() or Convert.ToBoolean(), however, I am unable to find anything that could do so for a Brush object.

My Brush object is used like this: Brushes.Black (Reference MSDN). I've looked at this thread, but the ways they input are either in RGB or Hexadecimal, which isn't what I need.

EDIT: If there is no way, or you can suggest better ways to use this, please let me know. Why I need a Brushes.XXXX is because I am drawing images onto bitmap objects.

Was it helpful?

Solution 2

If you need the properties in a list, I suggest you use List<object>. Since all classes in .NET derive from the object class, casting will be a lot more logic than casting a string to an object. Since you're using a list of objects, you don't need a class anymore to hold the properties. Also, you can use the object initializer to create the list instead of calling the Add() method every time. The assignment of the list will look like:

List<object> properties = new List<object>
{
    backgroundColor,
    textColor,
    timeOffset,
    dateOffset,
    title,
    showTitle,
    showText
};

And now you can pass this list to your method, like this:

YourListExpectingMethod(properties);

In the method you'll have to provide some logic to determine to which type to cast the object!

More reading:

OTHER TIPS

I would advise creating a class to hold all of this information:

public class MyDrawingInfo
{
    public Brush BackgroundColor;
    public Brush TextColor;
    public double TimeOffset;
    public double DateOffset;
    public string Title;
    public bool ShowTitle;
    public bool ShowText;
}

Now you can instantiate a class with this info, pass it around and not have to perform some crazy casting everywhere.

EDIT: To use this class, first instantiate it:

MyDrawingInfo mdi = new MyDrawingInfo();
mdi.BackgroundColor = Brushes.Black;
//etc

Then, when calling another method, pass the property you need:

ManualBackgroundColor(mdi.BackgroundColor)

Note: I updated the names of the properties and your method name. It is standard in C# to have your property and method names be Pascal Case

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top