This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why Would I Ever Need to Use C# Nested Classes
I'm doing it shorty, I have a class which looks like this:
namespace Blub {
public class ClassTest {
public void teest() {
return "test";
}
public class AnotherTest {
public void blub() {
return "test";
}
}
}
}
I can access to the function called "teest" like this, but how can I access to the function "blub" without doing another "new ClassTest.AnotherTest()"?
Accessing to the function teest:
Blub.ClassTest = new Blub.ClassTest();
ClassTest.teest(); //test will be returned
My try (and how I want it to, to access on AnotherTest is this:
Blub.ClassTest = new Blub.ClassTest();
ClassTest.blub(); //test will be returned
Which don't work, I can just access to AnotherTest like this, how I dont want it:
Blub.ClassTest2 = new Blub.ClassTest.AnotherTest();
ClassTest.blub(); //test will be returned
Does someone know a solutions for this?
You're declaring AnotherTest inside ClassTest, that's why you have to browse for it using namespace.class.2ndClass.
However, I suppose that you're not much aware of OO concepts, are you? If you declare a method inside a class, it will only be available for objects of that class, unless you declare it as static, what means that it would be a class method rather than a instance method.
If you want ClassTest to have 2 methods (teest and blub) simply declare both at the body of the class, like:
public class ClassTest
{
public string teest()
{
return "test";
}
public string blub()
{
return "test";
}
}
Also, note that if a method is declared as void it won't return anything (in fact, I think that your original code wouldn't even compile at all).
I'd recommend you to study OO a little deeper before trying to figure things out at your own.
If you need access to another class you have to make it a property in the first class.
namespace Blub {
public class AnotherTest {
public void blub() {
return "test";
}
}
public class ClassTest {
public AnotherTest at = new AnotherTest();
public void teest() {
return "test";
}
}
}
Then access it like this:
ClassTest x = new ClassTest();
x.at.blub();
Related
I'd like to have two simple calls in a class that would be transformed by other classes. Something like:
ObjectCreator.CreateBlank<Human>();
ObjectCreator.CreatePopulated<Human>();
ObjectCreator.CreateBlank<Dog>();
ObjectCreator.CreatePopulated<Dog>();
I currently do this:
public class ObjectCreator
{
public static T CreateBlank<T>()
{
return Activator.CreateInstance<T>();
}
public static T CreatePopulated<T>()
{
//Somehow return new object with populated properties
}
}
I am struggling with the populated part. I'd like it to return a "default" object of that type with defined properties. I've tried a few things involving passing in interfaces, but it gets messy fast (I don't expect this to be particularly clean either)
So If I called ObjectCreator.CreatePopulated(), I'd like it to somehow go to a different class where I create a new Anything, and fill it's properties to specific values. It feels like I'm close but missing a piece of the puzzle here.
My end game here is to have the call be as simple / readable as possible.
Any help is appreciated.
I DO realize it'd probably be easier to simply call a class that creates and populates each object, but this is a learning exercise for me and I'd like to attempt to get this working as generically as possible.
I would recommend doing something like this:
public interface IPopulatable
{
void Populate();
}
public class ObjectCreator
{
public static T CreateBlank<T>() where T : new ()
{
return new T();
}
public static T CreatePopulated<T>() where T : IPopulatable, new()
{
var populatable = new T();
populatable.Populate();
return populatable;
}
}
public class Human : IPopulatable
{
public string Name { get; set; }
public void Populate()
{
Name = "Joe";
}
}
I'm abit new in C#. I have some code like this:
namespace Example
{
public partial class Example_Setting : Form
{
public Example_Setting(String somethings)
{
}
private myPlace()
{
MessageBox.Show(somethings);
}
}
I don't know how to get value of somethings variable in myPlace().How can I do?
An example would be:
namespace Example
{
public partial class Example_Setting : Form
{
string somethings; // <-- declare a variable in the class
public Example_Setting(String somethings)
{
this.somethings = somethings; // save param to variable
}
private myPlace()
{
MessageBox.Show(somethings); // now data is here for use
}
}
I think you can use below code.Declaring the other variable and assign it into constructore and then you can use it in whole class.
public partial class Example_Setting : Form
{
public string some;
public Example_Setting(String somethings)
{
this.some = something;
}
private myPlace()
{
MessageBox.Show(this.some);
}
}
Others have already demonstrated an example. I just want to point out why you can't access somethings from myPlace.
In the example provided in your question, somethings is scoped locally to the constructor. That is, once the constructor has completed, somethings is no longer available to reference and use. In the examples others have provided, they scope somethings to the class, and then assign a the value provided in the constructor parameter. Since somethings is scoped to the class, your other methods (and properties) can access it. Note that if you use public, others outside of the class can use it as well. Best practice though is to keep it private and if you need public access, to use a property.
In a class, I have 2 methods. In method1 I created an object, but I can't use the same object in method2.
Why? Please help with a simple example.
The coding is too big, so I have given the layout
public class Sub
{
}
public class DataLoader
{
public void process1()
{
Sub obj = new Sub();
}
public void process2()
{
// here I can't use the object
}
}
The reason why this isn't working is scope. A local variable can only be accessed from the block it is declared in. To access it from multiple methods, add a field or pass it to the other method as a parameter.
Field:
class YourClass
{
object yourObject;
void Method1()
{
yourObject = new object();
}
void Method2()
{
int x = yourObject.GetHashCode();
}
}
Parameter:
class YourClass
{
void Method1()
{
Method2(new object());
}
void Method2(object theObject)
{
int x = theObject.GetHashCode();
}
}
You should use member variables in your class.
public class DataLoader
{
private Sub mySub;
public void Process1()
{
mySub = new Sub();
}
public void Process2()
{
if(mySub == null)
throw new InvalidOperationException("Called Process2 before Process1!");
// use mySub here
}
}
Read up on different variable scopes (specifically, instance variables in this case). You can also pass your object as a parameter, like codesparkle mentioned in their answer.
The short answer (without seeing your code) is that the object created in Method1 doesn't have any visibility, or scope, in Method2.
There are already some good answers here that show you how to solve your specific problem. But the real answer here is to familiarize yourself generally with the concept of Scope. It's a fundamental part of programming and learning more about it will help you tons.
There are many good articles and videos on the subject. This video is a great start. Good luck!
You have to set the object as a class field, then you can access it from every method of your class.
I am trying to set/read a variable in class bluRemote from another namespace/class like so:
namespace BluMote
{
class bluRemote
{
public string cableOrSat = "CABLE";
........
}
}
and the other cs file (which is the form):
namespace BluMote
{
public partial class SettingsForm : Form
{
if (BluMote.bluRemote.cableOrSat == "CABLE")
{
BluMote.bluRemote.cableOrSat = "SAT";
}
.......
}
}
I know i am doing it wrong but I'm more used to doing stuff like this in VB so its like night and day ha :o)
What you are trying to do is work with static variables so you would need to change your class to this:
namespace BluMote
{
public static class bluRemote
{
public static string cableOrSat = "CABLE";
........
}
}
It is better if you stay away from static classes (for the most part) and instead focus on an object oriented approach where you have an instance (object) of bluRemote.
So instead of making the bluRemote class static you keep it the same and do:
public partial class SettingsForm : Form
{
private bluRemote _remote = new bluRemote(); // possibly created somewhere else
public void SomeFunction()
{
if (_remote.cableOrSat == "CABLE")
{
_remote.cableOrSat = "SAT";
}
}
.......
}
You're trying to access an instance variable - i.e. one which has a potentially different value for each object - just by class name. That only works for static variables.
You need to have an instance of bluRemote, and ask that for its value. However, I would strongly suggest that:
You rename your class to follow .NET naming conventions
You don't make variables public; use properties
Also note that there's only one namespace here - BluMote. Both of your classes are declared in that namespace.
As you've declared the cableOrSat field, you'll need to set it on an instance of the bluRemote class, but you are trying to set it using the name of the class itself.
If you declare the cableOrSat field as:
public static string cableOrSat = "CABLE";
You will be able to access it through the class name itself.
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.