class properties - c#

I've just began using classes and would like to make some functions of a class visible outside that class. The problem is that I haven't got (and unable to have) a variable of type Abc.
Let me explain with a snippet of code:
class Abc
{
private float foo;
public float Foo {
get { return foo; }
set { foo = value; }
}
public static void Hello() {
foo = 5.0f;
Console.WriteLine("Hello everyone!");
}
}
.... somewhere else ....
Abc bar;
bar.Foo = 5.0f; // ok, I know this
bar.Hello(); // fine, I know this too
Abc.Hello(); // I'm trying to do this!
EDIT:
Ok, now suppose I would like to assign something to foo in Hello (as in my code). I know this might sound like a nonsense, so I'm not sure it's even possible.

You need a static member function. static member functions are not associated with a particular instance of the class, which is what you will need if you want to access them via the class itself. The specifics vary slightly depending on whether you're interested in C++ or C#.

Make Hello() static; that way it does not require an instantiation of the class.
public static void Hello() { ...

Related

Intercept Method/Property call in c#

In the code below I have a class Foo which is called (without an interface) by my main method. There is no backing field or setter for the property, instead it calls a private method. Foo cannot be changes, nor can the usage of foo be changed to an IFoo interface.
- How do I change the value of foo.FooValue?
- Is there anything in the System.Reflection, System.Reflection.Emit, .NET standard libraries etc (unsafe code, whatever) that I can include in a unit test to change the return value?
I appreciate if there is something it's bound to be quite "evil", but I am interested in "evil" answers.
public class Program
{
public static void Main(){
Foo foo = new Foo();
int bar = foo.FooValue;
}
}
public class Foo{
public int FooValue
{
get
{
return this.FooMethod();
}
}
private int FooMethod
{
return 0;
}
}
Related questions:
How to set value of property where there is no setter - Related but unanswered - Maybe the answer is "no", but I'm not convinced by the top answer which merely points out you can't achive this by changing a (non-existent) backing field.
Intercept call to property get method in C# - Interesting. Not sure whether this is my answer and if it is, not sure how it could be used in a unit test.
EDIT: Okay. I'm going to re-write my code to make it more testable. However, out of interest, has anyone out there successfully hacked their way through this situation?
You could create a proxy for Foo that could be mocked:
public class FooProxy : IFoo
{
private Foo _Foo;
public FooProxy(Foo foo)
{
_Foo = foo;
}
public int FooValue
{
get {return _Foo.FooValue();
}
}
public interface IFoo
{
public int FooValue {get;}
}
then you can use DI to "inject" an IFoo and make your code more testable.

C#: Giving access to private members without 3-fold code duplication

I have a class
public class Foo{
public Foo{...}
private void someFunction(){...}
...
private Acessor{
new Acessor
}
}
with some private functionality (someFunction). However, sometimes, I want to allow another class to call Foo.SomeFunction, so I have an inner class access Foo and pass out that:
public class Foo{
public Foo{...}
private void someFunction(){...}
...
public Acessor{
Foo _myFoo;
new Acessor(Foo foo){_myFoo = foo;}
public void someFunction(){
_myFoo.someFunction();
}
}
}
With this code, if I want a Foo to give someone else pemission to call someFunction, Foo can pass out a new Foo.Accessor(this).
Unfortunately, this code allows anyone to create a Foo.Accessor initiated with a Foo, and they can access someFunction! We don't want that. However, if we make Foo.Accessor private, then we can't pass it out of Foo.
My solution right now is to make Acessor a private class and let it implement a public interface IFooAccessor; then, I pass out the Foo.Accessor as an IFooAccessor. This works, but it means that I have to declaration every method that Foo.Accessor uses an extra time in IFooAccessor. Therefore, if I want to refactor the signature of this method (for example, by having someFunction take a parameter), I would need to introduce changes in three places. I've had to do this several times, and it is starting to really bother me. Is there a better way?
If someFunction has to be accessible for classes in the same assembly, use internal instead of private modifier.
http://msdn.microsoft.com/en-us/library/7c5ka91b(v=vs.71).aspx
If it has to be accessible for classes which are not in the same assemble then, it should be public. But, if it will be used by just a few classes in other assemblies, you probably should think better how you are organizing you code.
It's difficult to answer this question, since it's not clear (to me at least) what exactly you want to achieve. (You write make it difficult for someone to inadverdantly use this code in a comment).
Maybe, if the method is to be used in a special context only, then explicitly implementing an interface might be what you want:
public interface ISomeContract {
void someFunction();
}
public class Foo : ISomeContract {
public Foo() {...}
void ISomeContract.someFunction() {...}
}
This would mean, that a client of that class would have to cast it to ISomeContract to call someFunction():
var foo = new Foo();
var x = foo as ISomeContract;
x.someFunction();
I had a similar problem. A class that was simple, elegant and easy to understand, except for one ugly method that had to be called in one layer, that was not supposed to be called further down the food chain. Especially not by the consumers of this class.
What I ended up doing was to create an extension on my base class in a separate namespace that the normal callers of my classes would not be using. As my method needed private access this was combined with explicit interface implementation shown by M4N.
namespace MyProject.Whatever
{
internal interface IHidden
{
void Manipulate();
}
internal class MyClass : IHidden
{
private string privateMember = "World!";
public void SayHello()
{
Console.WriteLine("Hello " + privateMember);
}
void IHidden.Manipulate()
{
privateMember = "Universe!";
}
}
}
namespace MyProject.Whatever.Manipulatable
{
static class MyClassExtension
{
public static void Manipulate(this MyClass instance)
{
((IHidden)instance).Manipulate();
}
}
}

C# base() constructor order [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
C# constructor execution order
class Foo
{
public int abc;
Foo()
{
abc = 3;
}
}
class Bar : Foo
{
Bar() : base()
{
abc = 2;
}
}
In the example above, when an object of Bar is created, what will be the value of BarObject.abc? Is the base constructor called first, or is Bar() run, /then/ the base() constructor?
It'll be 2. Constructors run in order from base class first to inherited class last.
Note that initialisers (both static and instance variables) run in the opposite direction.
The full sequence is here: http://www.csharp411.com/c-object-initialization/
First base class constructor is called followed by the derived class constructor.
The result is 2. You should explicitly state the accessibility of that class variable.
Is it protected, private or public?
I see you changed it to public now, so it will be 2.
This link will further help you understand constructors, how they are used, when they are called, and order of constructor call when you use inheritance:
http://www.yoda.arachsys.com/csharp/constructors.html
Also you may want to actually try this out yourself, you will learn more by practicing and writing code then just reading it.
Try to declare Bar and output its value. Use some properties:
class Foo
{
public int abc;
public Foo()
{
abc = 3;
}
public int ABC
{
get { return abc; }
set { abc = value; }
}
}
class Bar : Foo
{
public Bar() : base()
{
abc = 2;
}
}
class Program
{
static void Main(string[] args)
{
Bar b = new Bar();
Console.WriteLine(b.ABC);
Console.ReadLine();
}
}
A simple printout would yield the result you are looking for. Here is the output:
Don't you just love my namespace :-). By the way you could also use automatic properties so that the property is simply public int ABC {get;set;}.
Assuming you make abc protected so that this compiles, it will be 2; however, base() is called first.
For stuff like this, write a simple test application and setup some breakpoints to find the answer.
The variable abc will be set to be 3 and then changed to be 2 (the base constructor is called first).
The base constructor will be called first, but this code does not compile. Private fields are not accesable from sub-classes. At the very least a field must be protected to be used in a sub-class.
But even knowing this, the behaviour you are attempting is confusing because it is surprising. Just the fact you had to ask which order things go in implies that it will get messed up when the order is forgotten.
The base constuctor is called first, and you would have a value of 2 for abc

Getting the instance that called the method in C#

I am looking for an algorithm that can get the object that called the method, within that method.
For instance:
public class Class1 {
public void Method () {
//the question
object a = ...;//the object that called the method (in this case object1)
//other instructions
}
}
public class Class2 {
public Class2 () {
Class1 myClass1 = new Class1();
myClass1.Method();
}
public static void Main () {
Class2 object1 = new Class2();
//...
}
}
Is there any way to do this?
Here's an example of how to do this...
...
using System.Diagnostics;
...
public class MyClass
{
/*...*/
//default level of two, will be 2 levels up from the GetCaller function.
private static string GetCaller(int level = 2)
{
var m = new StackTrace().GetFrame(level).GetMethod();
// .Name is the name only, .FullName includes the namespace
var className = m.DeclaringType.FullName;
//the method/function name you are looking for.
var methodName = m.Name;
//returns a composite of the namespace, class and method name.
return className + "->" + methodName;
}
public void DoSomething() {
//get the name of the class/method that called me.
var whoCalledMe = GetCaller();
//...
}
/*...*/
}
Posting this, because it took me a while to find what I was looking for myself. I'm using it in some static logger methods...
You could get to the current stack trace in code and walk up one step.
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
But as was commented below, this will get you the method and class calling you, but not the instance (if there is one, could be a static of course).
or just pass the object as method parameter.
public void Method(object callerObject)
{
..
}
and call the Method:
myClass.Method(this);
regards, Florian
It would be very bad style since
a) that would break encapsulation
b) it's impossible to know the type of the calling object at compile-time so whatever you do with the object later, it will propably not work.
c) it would be easier/better if you'd just pass the object to the constructor or the method, like:
Class1 c1 = new Class1(object1);
Obviously i don't know the exact details of your situation but this really seems like you need to rethink your structure a bit.
This could easily be done if proper inheritance is structured.
Consider looking into an abstract class and classes that inherit from said abstract class. You might even be able to accomplish the same thing with interfaces.

How to create a constructor that is only usable by a specific class. (C++ Friend equivalent in c#)

As far as I know, in C#, there is no support for the "friend" key word as in C++. Is there an alternative way to design a class that could achieve this same end result without resorting to the un-available "friend" key-word?
For those who don't already know, the Friend key word allows the programmer to specify that a member of class "X" can be accessed and used only by class "Y". But to any other class the member appears private so they cannot be accessed. Class "Y" does not have to inherit from class "X".
No, there is no way to do that in C#.
One common workaround is to based the object for which you want to hide the constructor on an interface. You can then use the other object to construct a private, nested class implementing that interface, and return it via a Factory. This prevents the outside world from constructing your object directly, since they only ever see and interact with the interface.
public interface IMyObject
{
void DoSomething();
}
public class MyFriendClass
{
IMyObject GetObject() { return new MyObject(); }
class MyObject : IMyObject
{
public void DoSomething() { // ... Do something here
}
}
}
This is how I solved it. I'm not sure if it's the "right" way to do it, but it required minimal effort:
public abstract class X
{
// "friend" member
protected X()
{
}
// a bunch of stuff that I didn't feel like shadowing in an interface
}
public class Y
{
private X _x;
public Y()
{
_x = new ConstructibleX();
}
public X GetX()
{
return _x;
}
private class ConstructibleX : X
{
public ConstructibleX()
: base()
{}
}
}
No. The closest you have is an internal constructor, or a private constructor and a separate factory method (probably internal, so you haven't saved much).
What about just having it explicity implement an interface that is only visible to a certain class?
Something like:
public void IFreindOfX.Foo() //This is a method in the class that's a 'friend' to class X.
{
/* Do Stuff */
}
and then make sure IFriendOfX is visible to class X. In your X class you'd call the method by first casting X to IFriendOfX then calling Foo(). Another advantage is that is is fairly self documenting... that is, it's pretty close to having the friend keyword itself.
What about creating a private class? This does exactly what you seem to be describing. A member of class X can be accessed and used only by class Y, and to any other class it appears private, since, well, it is private:
public class Y
{
private class X { }
private X Friend;
public Y()
{
Friend = new X();
}
}
As far as I know, the Internal keyword is the closest thing in .NET. This question will shed more light on Internal: Internal in C#
The only thing I can think of that would even come close would be protected internal but that does not restrict it to a specific class. The only friending I'm aware of in c# is to make a friend assembly. Still does not restrict to a specific class.
The only thing I could think of to try and do it would be to do something like the following:
public class A
{
public A() {}
protected internal A(B b) {}
}
public class B
{
A myVersion;
public B()
{
myVersion = A(this);
}
}
The only other way I could think of would be to do some sort of Constructor Injection using reflection that is done inside of your friend class. The injection mechanism would allow you to limit it to what you want but could be very cumbersome. Take a look at something like Spring.Net for some injection capabilities.
As a workaround, I suppose you could create a conditional in your constructor that uses reflection.
For example, if Class1's constructor must be called by Class2:
public Class1()
{
string callingClass = new StackFrame(1).GetMethod().DeclaringType.Name;
if (callingClass != "Class2")
{
throw new ApplicationException(
string.Concat("Class1 constructor can not be called by ",
callingClass, "."));
}
}
EDIT:
Please note that I would never actually do this in "real" code. Technically it works, but it's pretty nasty. I just thought it was creative. :)
You can access private members/methods using Reflection.
Since it's got the design tag, I never particularly liked the friend keyword. It pierces encapsulation and that always felt dirty to me.
This has a bit of a smell. There are other plenty of other ways to achieve implementation hiding in C#. Limiting construction to only specific classes does not achieve all that much.
Could you please provide more information as to the purpose of this requirement? As already answered, internal is the closest match for limiting accessibility to the class. There are ways to build on top of that depending on the purpose.

Categories

Resources