Quote (Minkomonster @ 24 Feb 2016 23:33)
I was hoping you could help me out, mate.
You see if I have this Java program here:
And I tried to port it over to C#
Code
public abstract class Bag<T>
{
public static int Capactity { get; set; }
}
public class BagOfStrings : Bag<String>
{
public BagOfStrings()
{
Capactity = 10;
}
}
public class BagOfBooleans : Bag<Boolean>
{
public BagOfBooleans()
{
Capactity = 20;
}
}
public class Program
{
static void Main(string[] args)
{
Bag<String> strings = new BagOfStrings();
Bag<Boolean> booleans = new BagOfBooleans();
Console.WriteLine(BagOfStrings.Capactity);
Console.WriteLine(BagOfBooleans.Capactity);
Console.Read();
}
}
Can you tell me what the issue is? Can you explain the difference between how generics are handled between the two languages? What does C# do differently than Java?
I don't see any issue?
C# generics are a part of the language all the way through the CLR, and generics in Java are (afaik) compiled to typecasts and are not "real" generics.
You can use simple type notation in C# (can use string in lower case and Boolean -> bool in C#, not that it matters though)
*edit:
I ran the program in Java and the output is different so I guess I was wrong.
I think it has something to do with how abstract classes work in Java vs C# but I'm not entirely sure, as I don't code in Java.
Each instantiation you do (in your C# example) of BagOfStrings and BagOfBooleans calls the individual constructors.
The reason I think that they aren't the same value when printing to the console, is that you print the value of the integer for each individual instance, even though it's a static variable.
Abstract classes in C# aren't meant to be instantiated, so I think (I'm not 100% on this) that you simply have the static variable as a member of each BagOfStrings and BagOfBooleans, rather than them sharing the same static variable from their parent class, because the abstract class is never instantiated.
This post was edited by Klexmoo on Mar 9 2016 06:53am