How to initialize a static property before initializing a static class? - c#

Below Class2 has a property that needs to be set before GetSomething is called, however because I access Class2 at the top of Class1 the property is always null when it gets to Something class. I can't seem to figure out how to change my code to set the property before it's used. Anyone?
EDIT
I want to pass the dependency from form1's constructor, not hardcode it further up the chain.
public partial class form1
{
private static readonly ISomeConstructedClass someConstructedClass = Class1.SomeConstructedClass;
public form1()
{
someConstructedClass.SomeDependency = new SomeDependency();
someConstructedClass.Whatever();
}
}
public static class Class1
{
public static readonly ISomething something = (ISomething)Class2.GetSomething("something");
public static ISomeConstructedClass SomeConstructedClass
{
get
{
return something.SomeConstructedClass;
}
}
}
....
}
public class Class2
{
public static ISomeDependency SomeDependency
{
get;
set;
}
public static GetSomething(string something)
{
switch(something)
{
case "something":
return new Something( SomeDependency );
}
}
}
public class Something : ISomething
{
public ISomeDependency SomeDependency
{
get;
set;
}
public Something(ISomeDependency someDependency)
{
SomeDependency = someDependency;
}
}

[Re]Edit:
I was confused about what you were trying to do before, you just need to create the dependency first.
public partial class form1
{
private static /*readonly*/ ISomeConstructedClass someConstructedClass;
public form1()
{
Class2.SomeDependency = new SomeDependency();
someConstructedClass = Class1.SomeConstructedClass;
someConstructedClass.Whatever();
}
}
I would also move the creation of something into the property just to make sure it is not initialized too soon (before the form1 constructor is called).
public static class Class1
{
public static ISomething something;
public static ISomeConstructedClass SomeConstructedClass
{
get
{
if (something == null) {
something = (ISomething)Class2.GetSomething("something");
}
return something.SomeConstructedClass;
}
}
}
You can use a static constructor. This is called before any static (or instance for that matter) fields or methods are called/accessed.
Something like:
static Class2() {
SomeDependency = SomeDependencyYouNeed;
}

Why are you using static methods? It looks like you're attempting a sort of Dependency Injection. Either create an instance of Class2 and pass the dependency in the constructor (and don't use static methods), or pass the dependency as a parameter of the GetSomething() method.
public static GetSomething(string something, ISomeDependency dependency).

Related

C# access static method from class object

I cant access static method from new object and not allow create same name non-static method.I need to use same name method static and non-static.
Foo class has some default variables. I create new object and set default variables.
Sample code block
class Foo
{
public void abc()
{
//...
}
public static string xyz(string s)
{
return "bla bla";
}
}
public void btn1_click()
{
System.Windows.Forms.MessageBox.Show(Foo.xyz("value"));
//Works OK
}
public void btn1_click()
{
Foo f1=new Foo();
//f1..
f1.xyz("value");
//Cant access non static method.
}
Thanks in advance.
If the class has default values, the correct place to populate them is in the class constructor:
public class Foo
{
public Foo()
{
// set default values here.
}
}
If you still want to use these default values as static members - no problem:
public class Foo
{
public static const int DEFAULT_INT_VALUE = 5;
public Foo()
{
IntValue = DEFAULT_INT_VALUE;
}
public int IntValue {get;set;}
}

Attribute to mark as "internal use"

I made a class which requires the public default constructor but
that is never called; instead another constructor is used at DataGrid.AddingNewItem.
I'd like to tell developers that the default constructor is not for their use.
Is there an attribute which suits the purpose?
I had checked DebuggerNonUserCode and MethodImplAttribute with MethodImplAttributes.InternalCall but not sure that's the proper approach.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.dataGrid1.CanUserAddRows = true;
var list = new List<RowX>();
this.dataGrid1.ItemsSource = CollectionViewSource.GetDefaultView(list);
this.dataGrid1.AddingNewItem += (s, e) => e.NewItem = new RowX("ABC");
}
}
public class RowX
{
public RowX()
{
//this is not used. but CollectionView require this to be public or
//CanUserAddRows doesn't work.
}
public RowX(object o)
{
//this is the actual ctor.
}
public string Text { get; set; }
}
Mark it private
class Foo
{
private Foo() {}
}
You can give your constructor an access modifier.
private This means it can only be called from another constructor in that class.
public class PrivateClass
{
//Only from inside this class:
private PrivateClass()
{
}
public static PrivateClass GetPrivateClass()
{
//This calls the private constructor so you can control exactly what happens
return new PrivateClass();
}
}
internal This means only code in the same assembly (i.e. from inside your library) can access it.
public class InternalClass
{
//Only from within the same assembly
internal InternalClass(string foo)
{
}
}

Reaching public property of parent class

a simple question :
public class class1
{
public string string1;
public class class2
{
public string string2
{
get{ string tmp = class1.string1; }
}
}
}
I want to be able to reach class1.string1 from class2.string2.get, but I cant. What would you recommend me to change, so that I can do that?
Thanx
Passing class1 reference to class2 in constructor:
public class class1 {
public string string1;
public class class2 {
private class1 _Reference;
public class2(class1 reference) {
if (reference == null) {
throw new ArgumentNullException("reference");
}
_Reference = reference;
}
public string string2 {
get { return _Reference.string1; }
}
}
}
Passing class1 reference to class2 after both classes have been created:
public class class1 {
public string string1;
public class class2 {
private class1 _Reference;
public class1 Reference {
set { _Reference = value; }
}
public string string2 {
get { return _Reference.string1; }
}
}
}
static void usage() {
var foo = new class1();
var bar = new class1.class2();
bar.Reference = foo;
string value = bar.string2;
}
There is no means of accessing a class from within a nested class that I know of. Class nesting doesn't lead to automatic instantiation of the surrounding class, it's just a (usually rather smelly) means of structuring your code.
You would either need a reference to an actual instance of Class1 inside Class2 or you'd need a static method on Class1.
Another way to accomplish this would be to use inheritance, but that's a whole different beast to tame:
public class Class1 {
protected String String1 { get; set; }
}
public class Class2 : Class1 {
public String String2 {
get {
String PropertyFromClass1 = base.String1;
// ...
}
}
}
That said: Your code wouldn't compile, string2's getter doesn't return anything. And please make yourself familiar with C#'s naming conventions.
Thanx for the suggestions. Due to the specific nature of the code, I had to solve this situation with a global public static class in another namespace.
Coming from Java I faced this "problem" when I started developing in C#.
As clearly explained by Dennis Traub and in this article in C# you can't access outer class members or methods. So you have to implement what in Java happens automatically:
class OuterClass {
string s;
// ...
class InnerClass {
OuterClass o_;
public InnerClass(OuterClass o) { o_ = o; }
public string GetOuterString() { return o_.s; }
}
void SomeFunction() {
InnerClass i = new InnerClass(this);
i.GetOuterString();
}
}

MEF plugins have no data from host

I'm trying to put config data from host to plugins but I always get nulls at plugins. My code responsible for plugins is below:
Form:
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent();
DataStorage.Instance.LoadModes();
DataStorage.Instance.ActiveMode = "aaa";
DataStorage.Instance.RulesFile = "bbb";
DataStorage.Instance.SetProjectName("cccc");
DataStorage.Instance.LoadRules();
DataStorage.Instance.LoadPlugins();
}
}
DataStorage:
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(ConfigStorage))]
public class DataStorage: ConfigStorage
{
//fields and properties here
public string ActiveMode;
[ImportMany(typeof (IAPlugin))]
public IEnumerable<Lazy<IAPlugin, IAPluginData>> aPlugins;
[ImportMany(typeof (IBPlugin))]
public IEnumerable<Lazy<IBPlugin, IBPluginData>> bPlugins;
private CompositionContainer _container;
private static readonly DataStorage instance = new DataStorage();
static DataStorage()
{
}
private DataStorage()
{
Init();
}
public static DataStorage Instance
{
get { return instance; }
}
private void Init()
{
//code here
}
public void LoadPlugins()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(typeof(ConfigStorage).Assembly));
catalog.Catalogs.Add(new DirectoryCatalog(Settings.Default.GetPathFor("Plugins")));
_container = new CompositionContainer(catalog);
try
{
_container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
}
ConfigStorage:
public abstract class ConfigStorage
{
public string RulesFile;
public string ActiveMode;
//properties and methods
}
Plugin:
[Export(typeof (IAPlugin))]
[ExportMetadata("Name", "myNameIsBond")]
public class myNameIsBond : IAPlugin
{
protected readonly ConfigStorage configStorage;
[ImportingConstructor]
public myNameIsBond (ConfigStorage configStorage)
{
if (configStorage == null)
throw new ArgumentNullException("configStorage");
this.configStorage = configStorage;
}
public string DoStep(string url)
{
Console.WriteLine(configStorage.ActiveMode); //this is null - it should be "aaa"
return url;
}
}
When I run plugin.Value.DoStep("sth"); the Console.WriteLine(configStorage.ActiveMode); always print null - when I debugging: all fields from configStorage are nulls. What I'm doing wrong? How can I put DataStorage instance to my plugins?
I think the problem is that the ConfigStorage export is showing up in the catalog, so the imports are getting satisfied with a version created by the catalog instead of the singleton you have configured. Try putting a PartNotDiscoverableAttribute on the DataStorage class.
As an aside, your DataStorage constructor is private, but it looks like the catalog can still create a separate version of it because the constructor is invoked through reflection.
I typically don't use an instance variable at all and just let MEF create the singleton, but if you really want to have an instance property you can do something like
// note that there is no export attribute here
public class DataStorage: ConfigStorage
{
[Export(typeof(ConfigStorage))]
public static DataStorage instance { get; private set; }
}
So that MEF will export your singleton instance rather than creating a new object.

How can I make one class solely responsible for creating and providing access to another class

This is how I understand I can implement the singleton pattern in C#:
public class ChesneyHawkes{
private static ChesneyHawkes _instance = new ChesneyHawkes();
public ChesneyHawkes Instance {get{return _instance;}}
private ChesneyHawkes()
{
}
}
What if I want to provide a single instance of an object, so that there can only ever be one, make the access to it public, but only allow it to be created or replaced by another singleton.
// The PuppetMaster should be the only class that
// can create the only existing Puppet instance.
public class PuppetMaster{
private static PuppetMaster_instance = new PuppetMaster();
public static PuppetMaster Instance {get{return _instance;}}
// Like a singleton but can be replaced at the whim of PuppetMaster.Instance
public static Puppet PuppetInstance {get {return Puppet;}}
private PuppetMaster()
{
}
public class Puppet{
// Please excuse the pseudo-access-modifier
puppetmasteronly Puppet(){
}
}
}
// To be accessed like so.
PuppetMaster.Puppet puppet = PuppetMaster.Instance.PuppetInstance;
You don't really need more than one singleton for that. Look at this example:
using System;
// interface for the "inner singleton"
interface IPuppet {
void DoSomething();
}
class MasterOfPuppets {
// private class: only MasterOfPuppets can create
private class PuppetImpl : IPuppet {
public void DoSomething() {
}
}
static MasterOfPuppets _instance = new MasterOfPuppets();
public static MasterOfPuppets Instance {
get { return _instance; }
}
// private set accessor: only MasterOfPuppets can replace instance
public IPuppet Puppet {
get;
private set;
}
}
class Program {
public static void Main(params string[] args) {
// access singleton and then inner instance
MasterOfPuppets.Instance.Puppet.DoSomething();
}
}

Categories

Resources