I am trying to add static class as a resources in Application.Resources
namespace MultiResImageChooser
{
public static class MultiResObjectInstance
{
private static MultiResPropertyChanged multiResObject = new MultiResPropertyChanged();
public static MultiResPropertyChanged current
{
get
{
return multiResObject;
}
}
}
}
Then in App.xaml I have
xmlns:static="clr-namespace:MultiResImageChooser"
....
<Application.Resources>
<static:MultiResObjectInstance x:Key="MultiResObjectInstance"/>
</Application.Resources>`
But in design view, VS2012 complains that The type MultiResObjectInstance is an abstract and must include an explicit value
How do I properly include static class in App.xaml as a resource?
Note sure giving a key for it because it is static.
You can't get an instance of a static class.
I think the problem is being static already. XAML tries to get an instance of the type and can't do it so thinks it is an abstract...
Related
Is there anyway for a static class to use values set in another static class from a different namespace to initialize some of it's members? Is there anyway to dictate the order they get established in?
e.g.
namespace Utility
{
using Config;
public static class Utility
{
public static UtilityObject myUtil = new UtilityObject(ConfigContext.myValue)
}
}
...
// somewhere in a different file/project
...
namespace Config
{
public static class ConfigContext
{
public static string myValue => ConfigurationManager.AppSettings["key"];
}
}
This is a simplified example of the basic pattern I'm trying to accomplish; I would like to take values that are in a config file which are loaded into static class ConfigContext , and use them to initialize members of a static class Utility .
You can't dictate the order of static initialization. But you can avoid the problem entirely by deferring initialization using lazy logic.
public static class Utility
{
private static Lazy<UtilityObject> _myUtil = null;
private static Utility()
{
_myUtil = new Lazy<UtilityObject>( () => new UtilityObject(ConfigContext.myValue) );
}
public static myUtil => _myUtil.Value;
}
Using this technique, the utility object isn't initialized until it is actually used.
If the logic to initialize ConfigContext has a similar issue, you can use a Lazy there too, and all of your lazy fields will get initialized in a cascading fashion, in the order they are needed.
I want use a static class that must contains global variables, so I can access to all application controls simply from a variable.
Actually I've this implementation:
public static class Globals
{
public static HeadToHead Head2Head
{
get { return Resources.Controls.HeadToHead; }
}
}
in the case above, I want return the instance of HeadToHead control, the control look like this:
public partial class HeadToHead : UserControl
{
public static int HomeId = 0;
}
my goal is to access to the static variables of this control, like: Globals.Head2Head.HomeId
but I get this error on this line: get { return Resources.Controls.HeadToHead; }
HeadToHead is a type which is not valid in the given context
You're returning what looks like a type from a property that seems to be declaring an instance of that type. If you truly want to return that type, there's syntax for that (I don't remember any more, I think in c# it's classname.type). If you want to return an instance, then you need to get that instance from somewhere.
As an aside, static instances of UI controls are a bad idea, and a code smell.
You have to instantiate an instance of the type and return that. As you want a single global instance you could use the static constructor.
public static class Globals {
static Globals(){
Head2Head = new Resources.Controls.HeadToHead();
}
public static HeadToHead Head2Head { get; private set; }
}
There are few situations in which you would actually want to do this but common static settings that do not change in the life of the application might be one of them. As HeadToHead inherits from UserControl that does not really seem to be the case, an instance of a UserControl should ideally never be static.
I have a static ExceptionHelper that looks like this:
public static class ExceptionHelper
{
public static async void ShowDialog(string message)
{
// Show message
}
}
Whenever I want to call this method I do it like this at the moment:
ExceptionHelper.ShowDialog("This is a message.");
I now thought of defining an alias for the ExceptionHelper to not having to write the whole word each time I want to use it.
I know I can achieve it with using:
using Ex = MyNamespaces.ExceptionHelper;
But then I'd have to define it in each file I want to use the method. Is there a way I can define the alias globally without changing the name of the class? Or is there any attribute I can set above the class declaration?
Extension Method
You could make it an extension method on string.
public static class ExceptionHelper
{
public static async void ShowDialog(this string message)
{
// Show message
}
}
Then you would use it like so:
using WhateverNamespaceExceptionHelperLivesIn;
public class TestClass
{
public void TestMethod()
{
"This is a message".ShowDialog();
}
}
This makes your question moot - you don't have to define an alias at all.
Static imports
An alternative approach is to import the class statically. You won't need an alias, because you can reference the ShowDialog method directly. This will require C#6/Visual Studio 2015.
using static WhateverNamespaceExceptionHelperLivesIn.ExceptionHelper;
public class TestClass
{
public void TestMethod()
{
ShowDialog("This is a message");
}
}
In C# 6.0 you can use static usings:
using static MyNamespace.ExceptionHelper;
Of course not globally, that works only for defines. But in a file where you use this line, you can use the members of the ExceptionHelper without any prefix.
As of C# 10, you can now define gloabl usings.
// GlobalUsing.cs
global using static WhateverNamespaceExceptionHelperLivesIn.ExceptionHelper;
And it will now be available globally, without having to define the class name, or the namespace, at the top of each class.
// Available Globally in the Project
public class TestClass
{
public void TestMethod()
{
ShowDialog("This is a message");
}
}
This might apply, even though you are using a method. You could use an ENUM type instead that lies outside of any namespace and access globals values that way. Place the enum in a file outside of any namespace. You can access it globally that way, or if you have trouble, using the "global" keyword below if you have any trouble referencing it:
enum Size
{
SMALL = 1,
MEDIUM = 5,
LARGE = 10
}
class Test {
int mysize1 = (int)Size.SMALL;
int mysize2 = (int)global::Size.MEDIUM;
}
I have some code base which has is calling the following:
SetHazardDataService();
namespace Analytics.Foo.DataServices
{
class HDB:IDataService
{
}
}
With a member function declared in another class/file
using Analytics.Foo.DataServices
public void MyDataService()
{
var DbDataSvc = new HDB();
}
originally, I see the same definition used elsewhere but with (no idea if that works):
protected void MyDataService()
I included the public method in my class
I'm now trying to recreate that functionality, but I get the following issue:
The type Analytics.Foo.DataServices.HDB' has no constructors defined
I'm not sure what the issue is - any suggestions for why this is the case. There is no constructor that I can see. Plus I'm not able to see the other code working/but it doesn't give the same issue.
You need to create a constructor to class HDB, like this:
namespace Analytics.Foo.DataServices
{
class HDB:IDataService
{
public HDB()
{
}
}
}
I want to define a global structure in C# and use it in three separate subroutines. I have already created the structure but I don't know how to make it a global variable so I can use it in multiple sections of my code. Any help is appreciated.
public struct Simple
{
public int Position;
public bool Exists;
public double LastValue;
};
static void Main(string[] args)
{
Simple s;
s.Position = 1;
s.Exists = false;
s.LastValue = 5.5;
}
So I want to use a Simple structure in two other routines in my code and possible pass it to different form (multiple usage of one variable).
The closest thing to "global" in C# is "static". Simply define the class and all members as static and it'll be accessible from anywhere the containing namespace is referenced. EDIT as Servy correctly points out, the class itself does not have to be static; however doing so forces all members to be static at compile-time. Also, static members can have any visibility, so you can have a private static field used by a public static property or method, and you can have an internal static class that won't be visible outside its home assembly. Just being static doesn't automatically make it wide open.
However, a better pattern might be the Singleton; you define a class that has one static instance of itself, that can then be passed around. The benefit is that you can still deal with the object as an instance class if you want to, but the same instance is available everywhere using a static getter. Here's some reading material: http://csharpindepth.com/Articles/General/Singleton.aspx
In your case it appears that you have a object as a local variable in your main method that you need to use in another method. The appropriate solution in this context is to add a parameter to that other method. Take a look at this example:
public class MyObject
{
public int Value;
}
public static void Main(string[] args)
{
MyObject obj = new MyObject();
obj.Value = 42;
PrintObject(obj);
Console.WriteLine("Press any key to exit...");
Console.ReadKey(true);
}
public static void PrintObject(MyObject obj)
{
Console.WriteLine(obj.Value);
}