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;}
}
Related
I wrote the code below and i want to access the private varibale in another class, i created instance of the class and tried to access it but couldn't. can someone point out what I did wrong in the code below?
using System;
namespace lab_first
{
public class AccessModifiers
{
private int Abc { get; set; }
private int bcd { get; set; }
}
class Program
{
static void Main(string[] args)
{
var acc = new AccessModifiers();
Console.WriteLine(acc.Abc)
}
}
}
You make members private so that nobody outside the class can access them.
This goes inline with the principle of information hiding.
Your example should look like this:
public class AccessModifiers
{
// You can only access this inside of the class AccessModifiers
private int Abc { get; set; }
internal void SetValue(int x){
// Access possible, because SetValue() is inside the same class
Abc = x;
}
internal int GetValue(){
// Access possible, because GetValue() is inside the same class
return Abc;
}
}
class Program
{
static void Main(string[] args)
{
var acc = new AccessModifiers();
// Abc is never modified directly, only indirectly.
acc.SetValue(5);
Console.WriteLine(acc.GetValue());
}
}
However, there is still a way to access the private member. It's called Reflection. However, note that private variables are considered an implementation detail and might change at any time, so you can't rely on it. E.g. someone might change the name from Abc to def and your Reflection-based approach fails.
You can either change private to internal or public in this case.
Another way is declaring the variables in the class as private and using C# Properties in the class to set and get the values of variables. this is called encapsulation which is a protective shield that prevents the data from being accessed by the code outside this shield).
public class AccessModifiers
{
private int _abc { get; set; }
private int _bcd { get; set; }
public int Abc
{
get
{
return _abc;
}
set
{
_abc = value;
}
}
public int Bcd
{
get
{
return _bcd;
}
set
{
_bcd = value;
}
}
}
Is it possible to to define a string from a variable where the string does NOT have quotations. Example:
public class aclass
{
public string athing;
}
public void example(string thing)
{
aclass thing = new aclass();
}
The string thing can't be put into aclass thing = new aclass(); normaly.
Is there anyway to do it?
You need a constructor
void Main()
{
CreateExampleObject("testing");
}
public class Example
{
// This is a constructor that requires a string as an argument
public Example(string text)
{
this.Text = text;
}
public string Text { get; set; }
}
public void CreateExampleObject(string text)
{
Example example = new Example(text);
Console.WriteLine(example.Text);
}
You can do it this using many way but generally standard way is using constructor
please refer this link for better understanding.
C# : assign data to properties via constructor vs. instantiating
You have to ways of setting fields/property value of an object.
First is to do it through the constructor, as mentioned in other answer.
Second can be implmeneted in various ways:
Expose public property making field privte:
public class aclass
{
private string _athing;
public string Athing
{
get { return _athing; }
set { _athing = value; }
}
}
public void example(string thing)
{
aclass aclass = new aclass();
aclass.Athing = thing;
}
Or even shorter, you could use property:
public class aclass
{
public string Athing {get; set; }
}
Using your implementation, you make your field public, so you can set it easily:
public void example(string thing)
{
aclass aclass = new aclass();
aclass.athing = thing;
}
But it doesn't comply with OOP encapsulation principle.
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).
I have such class in c#:
public class Foo
{
public static readonly int SIZE = 2;
private int[] array;
public Foo
{
array = new int[SIZE];
}
}
and Bar class:
public class Bar : Foo
{
public static readonly int SIZE = 4;
}
What I want to accopmlish is to create a Bar instance with array size taken from overrided SIZE value. How to do it properly?
You can't do it this way. You could use a virtual method:
public class Foo
{
protected virtual int GetSize(){return 2;};
private int[] array;
public Foo
{
array = new int[GetSize()];
}
}
It's also possible to use reflection to look for a static field SIZE, but I don't recommend that.
Your SIZE constant is static, and static fields aren't inherited - Foo.SIZE and Bar.SIZE are two different constants that have nothing to do with each other. That's why Foo's constructor call will always initialize with 2, not 4.
What you can do is create a protected virtual void Initialize() method in Foo that initializes the array with 2, and override it in Bar to initialize it with 4.
You cannot inherit static fields; instead use the below:
public class Foo
{
protected virtual int SIZE
{
get
{
return 2;
}
}
private int[] array;
public Foo()
{
array = new int[SIZE];
}
}
public class Bar : Foo
{
protected override int SIZE
{
get
{
return 4;
}
}
}
Virtual is like saying "This is the default value of the base class"; whilst Override changes the value on the class implementing "Foo".
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();
}
}