Why can't I call a public method in another class? - c#

I have got these two classes interacting and I am trying to call four different classes from class one for use in class two.
The methods are public and they do return values but for some reason there is not a connection being made.
The error I get when I try is: "An object reference is required for the nonstatic field, method, or property 'GradeBook.[method I want called]'"
I have everything initialized. I don't want to create the methods as static. I read over the specifics of my assignment again and I'm not even supposed to but I can't seem to get this to work anyway I word it.
myGradeBook.[method]
GraceBook.[method]
It all seems to create errors.
The current errors:
The best overloaded method match or 'System.Console.WriteLine(string, object)' has some invalid arguments.
Arugment '2': cannot convert from 'method group' to 'object'
I'm not even sur what those mean....
EDIT:
I just fixed that problem thanks to the Step Into feature of Visual Studio.
I don't know why it took me so long to use it.

You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example
class Example {
public static string NonInstanceMethod() {
return "static";
}
public string InstanceMethod() {
return "non-static";
}
}
static void SomeMethod() {
Console.WriteLine(Example.NonInstanceMethod());
Console.WriteLine(Example.InstanceMethod()); // Does not compile
Example v1 = new Example();
Console.WriteLine(v1.InstanceMethod());
}

It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.
MyClass myClass = new MyClass();
once you've added that line you can then call your method
myClass.myMethod();
Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.

You have to create a variable of the type of the class, and set it equal to a new instance of the object first.
GradeBook myGradeBook = new GradeBook();
Then call the method on the obect you just created.
myGradeBook.[method you want called]

For example 1 and 2 you need to create static methods:
public static string InstanceMethod() {return "Hello World";}
Then for example 3 you need an instance of your object to invoke the method:
object o = new object();
string s = o.InstanceMethod();

Related

C# Possible method to call protected non-static methods in current class?

I've recently picked up C# as another language to further my knowledge into other languages, but as experimenting to get used to the syntax of the language, I encountered this problem when using the public static void Main(); and calling methods inside the same class. My code was as follows:
namespace TestingProject
{
class Class1
{
public static void Main()
{
System.Console.WriteLine("This is nothing but a test \n Input 'test'");
var UserInput = System.Console.ReadLine();
string Input = this.ValidateInput(UserInput);
System.Console.WriteLine(Input);
System.Console.WriteLine();
}
protected string ValidateInput(string Variable)
{
var VarReturn = (string)null;
if (string.Equals(Variable, "test"))
{
VarReturn = "Correct \n";
}
else
{
VarReturn = "Incorrect \n";
}
return VarReturn;
}
}
}
So, from what i've researched it turns out that you cannot use the this syntax to call internal private methods from a static function.
So I tried self but this returned no avail (assuming since languages such as python, PHP allow self), so tried the following:
string Input = TestingProject.Class1.ValidateInput(UserInput);
To be presented with the following message:
Error 1 An object reference is required for the non-static field,
method, or property
'TestingProject.Class1.ValidateInput(string)' C:\Users\xxx\AppData\Local\Temporary
Projects\ClassProject\Class1.cs 14 28 ClassProject
So then, I found this little gem which did solve the problem :
var CurrClass = new Class1();
and called the protected method as so:
var CurrClass = new Class1();
string Input = CurrClass.ValidateInput(UserInput);
Which did surprise me that this was the only available way to call internal non-staic private methods, so my overall question is:
Is there a way to call non-static methods which are protected/private without initializing a new variable to contain the current object?
The problem is that your Main method is static. A static method can not access non-static methods, even within the same class, without having an instance of the object. That is the entire point of having a static method: you don't have a concrete object to work with. It's outside of the scope of the other instance methods.

Object reference not set to an instance of an object... but with interfaces. (C#)

The following two lines of code are causing an error in my program because of a NullReferenceException.
ISceneGraphFactory factory = null;
IGroupNode Root = factory.CreateGroupNode("Root", "GroupNode", null);
Both of these are interfaces. So basically I am trying to create that second interface IGroupNode with the factory. (The error occurs on the second line). Here is how the interfaces themselves look:
public interface ISceneGraphFactory
{
IDrawableNode CreateDrawableNode(string name, string DrawableType, object drawableData);
IGroupNode CreateGroupNode(string name, string groupType, object groupData);
IStateNode CreateStateNode(string name, string stateType, object stateData);
ITransformNode CreateTransformNode(string name, string transformType, object transformData);
}
public interface IGroupNode : ISceneNode, IEnumerable<ISceneNode>
{
void AddChild(ISceneNode child);
}
They are both functioning and have worked in other programs.
Does anyone know how to get rid of this error when working with interfaces? I think it is complaining because I am using interfaces here...
You need an object to call CreateGroupNode (since it is not static).
ISceneGraphFactory factory = null;
factory = new SomeClassThatImplementsISceneGraphFactory();
IGroupNode Root = factory.CreateGroupNode("Root", "GroupNode", null);
Some will point out not only is it not static it is "virtual" because it is only defined in an interface. In any case you need an object to call it.
The problem is pretty clear here. You're assigning null to variable, and then try to do a method call on that. It can't work (unless the method is an extension method, but just assume it's not).
ISceneGraphFactory factory = null;
IGroupNode Root = factory.CreateGroupNode("Root", "GroupNode", null);
You have to assign an object to factory before calling any method. And because you're declaring variable using the interface, your object has to be an instance of a class which implements ISceneGraphFactory.

I am having trouble assigning an Array?

I am having trouble with this piece of code and I can't figure out how to get it to work. I can't figure out what the problem is as to me it looks like it should work. The string array called m_nameList on both places are marked as 'An object reference required for the non static feild, method, or property 'Solutionname.classname.m_nameList'
the code:
public static bool CheckVacantSeats(int seatNumber)
{
if (m_nameList[seatNumber] == null)
{
return true;
}
return false;
}
m_nameList is an array that is declared in an constructor before this static bool:
public SeatManager(int maxNumberOfSeats)
{
m_totNumOfSeats = maxNumberOfSeats;
m_nameList = new string[m_totNumOfSeats];
m_priceList = new double[m_totNumOfSeats];
}
I am calling the CheckVacantSeat from another class with this:
bool validSeats = SeatManager.CheckVacantSeats(seatNumber, m_nameList);
I can't figure out what is wrong with it. So i need some help figuring out why m_nameList does not work for me?
Thanks in advance!!
//Regards
The problem is that you have marked your method as static. Since it is static, it has "no" state, and cannot access class members which are not marked as static.
You can mark m_nameList as static, but that means that it's value is shared across all reads and writes. m_nameList looks like a simple lookup table so maybe this is what you want?
Recommended reading is static and Static Classes and Static Members.
Your function is static, but your variables are not static.
Well your call is wrong for a start, your method CheckVacantSeats only accepts one parameter so you can't call it with two??!
CheckVacantSeats(int seatNumber)
SeatManager.CheckVacantSeats(seatNumber, m_nameList);
your method is also static so there's no point having a constructor.
I think what your after is:
SeatManager seatManager = new SeatManager(maxNumberOfSeats);
seatManager.CheckVacantSeats(seatNumber);
Also
public bool CheckVacantSeats(int seatNumber)
{
if (m_nameList[seatNumber] == null)
{
return true;
}
return false;
}
You are mixing two concepts: an instance initialized with a constructor, and a static class with static members. You cannot expect a static member method to access a non-static field. I guess your m_nameList field is static as well, otherwise your code wouldn't even compile. You should choose either way:
make all SeatManager's members non-static;
turn the SeatManager class into a static class having all members static.
Since you need to initialize the SeatManager with the total number of seats, the better way seems to be No. (1). Then instead of SeatManager.CheckVacantSeats() you would call an instance like mySeatManager.CheckVacantSeats(). Even in case there will always be just one instance of SeatManager — a singleton — this approach is better. With a singleton, you could end up with a public static SeatManager Instance { get; set; } property in SeatManager and work with it like this: SeatManager.Instace.CheckVacantSeats(). This is usually called a singleton pattern.

The type parameter cannot be used with type arguments

I wanted to code a helper method in Unit test project, which will initialize the presenter set the views instance to it and set the presenter state.
It threw me the exception:
the type parameter cannot be used with type arguments
Code:
public static **TPresenter<TView>** Initialize<TPresenter,TView>()
where TPresenter: BasePresenter<TView>, new()
where TView : new()
{
}
After couple of minutes I found the issue was with my return type TPresenter<Tview>
I read few posts which didn't clearly explain Why I'm not be able to say T1<T2>
I was forced to make the presenter assignment through reference parameter. Any explanations are welcome!
Basically there's no way of saying that a type parameter is itself a generic type with a particular number of type parameters - which you need to be able to do in order to make TPresenter<TView> make sense.
It's not clear what you mean by making it work via a reference parameter - whatever type you used for that ref parameter should be fine as a return type too. My guess is that it was just of type TPresenter, not TPresenter<TView>.
There is no such thing as a TPresenter<TView> it is meaningless. TPresenter is just a placeholder, until it is constrained by the where it could be anything, e.g. there is no int<tview> so you can't have that. Once you add the constraint it means it has to be a BasePresenter<TView> or some derived type so it will always be a Something<TView> so again TPresenter<TView> is meaningless.
This is an old one, but I hit it too. In the Class definition, just use the single type, then multiple types where you use it. E.g:
public class Template1<T>{}
void SomeFunc()
{
<Template1<SomeClass1,SomeClass2>> someValue = new <Template1<SomeClass1,SomeClass2>>()
}
//or even:
void SomeOtherFunc<U,V>()
{
<Template1<U,V>> someValue = new <Template1<U,V>>();
}
I was getting similar error in my code. #Jon Skeet correctly points to the right direction. The return type is already generic, as specified by TPresenter : BasePresenter<TView>. So we can simply use it as TPresenter instead of TPresenter<TView>.
public class BasePresenter<T>
{
}
public class Demo
{
public static TPresenter Initialize<TPresenter, TView>() where TPresenter: BasePresenter<TView>, new()
{
return null;
}
}
Small addition, I came here because i was trying to write an extension method;
public static T AutoJoinGroup<T, TD>(this T<TD> groupHubClientBase, string groupName)
where T : GroupHubClientBase<TD>
{
...
}
As you can see, I tried to use T<TD> which is incorrect, you can just use T

What do you mean by "extension methods" in C#?

Can anyone else explain this, (beginners approach). Thanks..
Extension Methods are just static methods in static classes that behaves like they were defined in other class.
In the first parameter before the type goes the keyword this wich indicates that is an extension method.
Example:
public static class Extensions
{
public static object ExtensionMethodForStrings( this string s, object otherParameter)
{
//....
return //whatever you want to return or not
}
}
This is an extension method on System.String that takes two parameters:
- string s : This is the instance variable
- object otherParameter: You can have as many as you want including none
You can call this method in two ways:
Static way:
string s = "Your string";
object o = new object(); // or whatever you want
object result = Extensions.ExtensionMethodForStrings(s,o);
Extension Method way
string s = "Your string";
object o = new object(); // or whatever you want
object result = s.ExtensionMethodForStrings(o);
In the second case it works as if the type string has an instance method called ExtensionMethodForStrings. Actually for the compiler the are equivalent.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
The C# article on Extension Methods.
An extension method is a static method in a static class whose first parameter is preceded by the keyword this.
The C# compiler has some syntactic sugar that can convert a call of x.Foo(bar) to SomeExtension.Foo(x, bar). This is used extensively by LINQ (Take, Skip, Where, Select, etc.) but you can also write your own extension methods if you wish.
This question includes lots of examples of useful extension methods:
What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)
An extension method is a method that behaves (somewhat) like it is a member of a class, but it is not a member of that class. It can be called on members of that class, but has no reference to the internals of the class.
Extension methods are static methods, and must be members of a static class.
public static class StringExtensions
{
public static string HtmlEncode(this string dataString)
{
return HttpServerUtility.HtmlEncode(dataString);
}
}
The keyword "this" prior to the first parameter type identifies this as an extension method, and the class it extends.
It would be used this way:
string foo = "bar";
string myOutput = foo.HtmlEncode();

Categories