Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I want to use Java style polymorphism in C#. Is it possible?
Here is an example that does not compile
using System;
namespace HelloWorld
{
public class Program
{
public static void Main (string[] args)
{
Triangle triangle = new Triangle(2);
Square square = new Square(3);
printID(square);
}
public void printID(Shape s){
Console.WriteLine ("id is " + s.id);
}
}
public class Shape{
public int id;
}
public class Triangle: Shape{
float b;
float height;
float area(){
return b*height/2;
}
public Triangle(int k){
id=k;
}
}
public class Square: Shape{
float side;
float area(){
return side*side;
}
public Square(int k){
id=k;
}
}
}
The message is
MyClass.cs(11,4): error CS0120: An object reference is required to access non-static member `HelloWorld.Program.printID(HelloWorld.Shape)'
Thanks!
Error is not related to polymorphism - you are calling non-static method from static method Main. You should make printID static as well.
public static void printID(Shape s){
Console.WriteLine("id is " + s.id);
}
Also I suggest you to:
Stick with C# naming guidelines when you are writing C# code. Methods and properties should have PascalCase names.
Use properties instead of public fields
If any shape should have and id, consider to create public Shape(int id) constructor in base class and call that constructor from derived classes via : base(id)
Improve naming - if you are passing id, then call variable id instead of k.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have these two classes:
public class SpawnStringClass{
public List<PlayerSpawn> playerSpawn;
}
public class PlayerSpawn
{
public string PlayerName;
public float posx;
public float posz;
}
I created a variable Referencing to the first class:
SpawnStringClass SpawnClass = new SpawnStringClass(){playerSpawn = new List<PlayerSpawn>()};
var item = new PlayerSpawn
{
PlayerName = player.NickName.ToString(),
posx = SpawnX,
posz = SpawnZ
};
SpawnClass.playerSpawn.Add(item);
Now when I try to convert the Spawn string class with the list to json it doesn'T work.
SpawnString = JsonUtility.ToJson(SpawnClass);
Debug.Log(SpawnString);
Does anyone know why?
The classes are outside of the main mono behaviour class and the variable player.nickname, SpawnX and SpawnZ are declared.
Thanks in advance!
The built-in JsonUtility uses the also built-in Unity serializer.
Refer to Script Serialization and in particular the section How to ensure a custom class can be serialized where you can find
Ensure it:
Has the [Serializable] attribute
Is not abstract
Is not static
Is not generic, though it may inherit from a generic class
Solution: Your both classes have to be attributed [Serializable]
[Serializable]
public class SpawnStringClass
{
public List<PlayerSpawn> playerSpawn;
}
[Serializable]
public class PlayerSpawn
{
public string PlayerName;
public float posx;
public float posz;
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
So I was following a c# tutorial the otherday (still a begginer) and I saw how the class ATMState was defined:
public abstract class ATMState
{
private ATM atm;
public ATM Atm
{
get { return atm; }
set { atm = value; }
}
private int dummyCashPresent = 1000;
public int DummyCashPresent
{
get { return dummyCashPresent; }
set { dummyCashPresent = value; }
}
public abstract string GetNextScreen();
}
To be honest, I find those declaraions rather confusing, so I decided to redo it in my own way:
public abstract class ATMState
{
public ATM Atm { get; set; }
public int DummyCashPresent { get; set; }
public ATMState()
{
DummyCashPresent = 1000;
}
public abstract string GetNextScreen();
}
What is the difference? Which one is better and why?
What is the difference?
You're using "automatic properties", the sample code is not. Perhaps the sample was written before automatic properties were introduced to C#.
Which one is better and why?
Generally automatic properties are better: more compact code is less to read and understanding. If you have no logic to put in the getter or setter you should be using automatic properties.
However, currently1 you cannot set a breakpoint on either the getter or setter of an automatic property, thus to be able to track accesses one sometimes need to break out with an explicit backing field.
1 I believe this will change in VS2015.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Improve this question
I am having ambiguity problems with some extension methods. I have several similar classes, and each has an extension method called "ToEntity." If more than one of these extension methods are brought into scope, the compiler doesn't know which to use, even though it seems it would be able to discern that by checking what extended class is trying to use it. Apparently this is not the case, but perhaps I've done something wrong? For example:
// these classes both have ToEntity() extension methods which return MyEntity
MyExtendedClass1 model1 = new MyExtendedClass1();
MyExtendedClass2 model2 = new MyExtendedClass2();
MyEntity myEntity1 = model1.ToEntity(); // ambiguous... why?
For the last few months I've taken a shortcut around this by calling one of the methods "ToEntity2()" which is super lame, especially now that I'm adding more classes that need to have a ToEntity() extension. Now I'm refactoring and hoping to find a better way. So I guess my explicit questions are:
Why are these methods ambiguous instead of being differentiated by the class they extend?
What are my options for a work-around?
Update: My extension methods would be defined like this:
public static class MyExtensions
{
public static MyEntity ToEntity(this MyExtendedClass1 myExtClass)
{
// do stuff with myExtClass
// eventually return a MyEntity
}
public static MyEntity ToEntity(this MyExtendedClass2 myExtClass)
{
// do stuff with myExtClass
// eventually return a MyEntity
}
}
Is one of your extension methods defined on an interface? This, for example, causes an ambiguous invocation error:
public static class Ext
{
public static void A(this IComparable<int> a) { }
public static void A(this ValueType a) { }
public static void CallSite() { 1.A(); }
}
The error is:
The call is ambiguous between the following methods or properties:
'Namespace.Ext.A(System.IComparable)' and
'Namespace.Ext.A(System.ValueType)'
If all the extension methods are defined on base classes, however, the ambiguity disappears. For example:
public static class Ext
{
public static void A(this Object a) { }
public static void A(this ValueType a) { }
public static void CallSite() { 1.A(); }
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In Windows application development using C# .NET, how do you make a global variable or global instance of a class, which can then be directly used by all other windows forms, e.g. form1, form2, etc.
You can create a static class and define a static variable inside it.
All the classes in your project can refer to it using MyGlobalVariables.GlobalVariable
public static class MyGlobalVariables
{
public static int GlobalVariable;
}
Create a public static class which holds the global variables
eg.
public static class GlobalValues
{
public static int UserId{get;set;}
}
Read more about C# Global Variable
Also I guess you should read about Classes and Structs
Create singleton class so that instace can be created once and used across application
public class Global
{
private static readonly Global instance = new Global();
public static Global Instance
{
get
{
return instance;
}
}
Global()
{
}
public string myproperty
{
get;set;
}
}
Usage:
Global.Instance.myproperty
Make it as a static variable and static class, e.g.
private static string foo = "this is static";
public static class Bar
{}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm creating a simulator of ecosystems where species can be used to simulate various diseases, my problem is that I start using 4 species but if I need more ... I need more variables to store, my question is, Is there any way through Reflection to let me create dynamic variables during the execution of an event in my program? Thank you! i'm using Windows Presentation Foundation and C#
The normal way to handle this is to have a base class for your disease species and then use a collection to hold them all:
public abstract class DiseaseBase
{
public abstract void Spread();
}
public class Anthrax : DiseaseBase
{
public override void Spread()
{
GetPostedToPolitician();
}
}
public class BirdFlu : DiseaseBase
{
public override void Spread()
{
Cluck();
SneezeOnHuman();
}
}
public class SwineFlu : DiseaseBase
{
public override void Spread()
{
//roll in mud around other piggies
}
}
public class ManFlu : DiseaseBase
{
public override void Spread()
{
//this is not contagious
//lie in bed and complain
//get girlfriend to make chicken soup
//serve chicken soup with beer and baseball/football/[A-Za-z0-9]+Ball
}
}
public List<DiseaseBase> DiseaseCollection = new List<Disease>();
So everything gets stored in the collection as the base class (DiseaseBase), and with the appropriate use of abstract methods in the base and/or interfaces you can always handle each disease instance as the base object.