I am converting Java into C# and have the following code (see discussion in Java Context about its use). One approach might be to create a separate file/class but is there a C# idom which preserves the intention in the Java code?
public class Foo {
// Foo fields and functions
// ...
private static class SGroup {
private static Map<Integer, SGroup> idMap = new HashMap<Integer, SGroup>();
public SGroup(int id, String type) {
// ...
}
}
}
All C# nested classes are like Java static nested classes:
C#:
class Outer
{
class Inner
{
}
}
Is like Java's:
class Outer
{
static class Inner
{
}
}
In other words, an instance of Inner doesn't have an implicit reference to an instance of Outer.
There isn't the equivalent of a Java inner class in C# though.
The accessibility rules are somewhat different between the two languages though: in C#, the code in the nested class has access to private members in the containing class; in Java all code declared within one top-level type has access to all the other private members declared within that same top-level type.
Give this a look
http://blogs.msdn.com/oldnewthing/archive/2006/08/01/685248.aspx
I am looking specifically at
In other words, Java inner classes are
syntactic sugar that is not available
to C#. In C#, you have to do it
manually.
If you want, you can create your own
sugar:
class OuterClass {
...
InnerClass NewInnerClass() {
return new InnerClass(this);
}
void SomeFunction() {
InnerClass i = this.NewInnerClass();
i.GetOuterString();
}
}
Where you would want to write in Java
new o.InnerClass(...) you can write in
C# either o.NewInnerClass(...) or new
InnerClass(o, ...). Yes, it's just a
bunch of moving the word new around.
Like I said, it's just sugar.
You can have a static nested class in C#, according to Nested Classes.
Related
Am new to C#, but have a plenty of experience of VB.net, now my issue is that there are no modules in C# and i need to define a class which is accessible in all classes and i don't know how to do it.
For example I have a "classProject" and I need to make it accessible everywhere, so in vb.net , I will define it in module like below.
Module ModuleMain
Public tProject As New ClassProject
End Module
Now, I need to do same in C#.
Thanks in advance.
You can do this in your case:
namespace MyProject
{
public static class classProject
{
int myIntvar = 0;
string myStringvar = "test";
}
}
And you can use this static class in your other classes like:
public class Test
{
int intTest = classProject.myIntvar; //will be 0
string stringTest = classProject.myStringvar; // will be test
}
You can use the variables in the static class since a static variable shares the value of it among all instances of the class. When you create multiple instances of classProject class, the variables myIntvar and myStringvar are shared across all of other classes in your project. Thus, at any given point of time, there will be only one integer and one string value contained in the respective variable's.
It sounds like you're looking for a static class. You can reference the access modifiers here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers
I think you need to extends your other classes to class father (ClassProject) And you can access to it with youur children classes.
//[access modifier] - [class] - [identifier]
public class Customer
{
// Fields, properties, methods and events go here...
}
see more
In C++ I can declare a fully functional anonymous class inside a piece of code where it's needed so that I don't have to declare it if I need it only once.
The code should be like this
Class MyClass
{
Class
{
String string1;
String string2;
void MyMethod();
} Strings;
}
And call it the members with MyClass.Strings.string1, MyClass.Strings.MyMethod() and so on. This way I can elegantly group my code.
Is there a way to do the same thing in C#?
This way I can elegantly group my code.
I don't how can this help you to elegantly group your code, but there is no such thing in C#. There are anonymous classes but they only work in local scopes:
// inside a method:
var obj = new { String1 = "Hello", String2 = "World" };
And you can't add methods to them.
The closest thing you can get to is an inner class/struct:
class MyClass
{
class MyStrings
{
String string1;
String string2;
void MyMethod() { ... }
}
MyStrings Strings;
}
I agree Sweeper. This functionality adds just cluttering code. You should consider to make your code as easy as possible to understand. This means if you feal that you want to group your code, giving every group it´s own functionality, why not make this group a class and give it a name that directly reflects what its purpose is.
What you can do is use an anonymous class which in C# doesn´t implement any interface but just derives from object:
var a = new { MyMember = 1, MyFunc = new Func<int>(() => 1) };
now you can invoke both members of this type:
Console.WriteLine(a.MyMember);
var retVal = a.myFunc();
But does this make your code any better in a way that it´s easier to understand what it does? I doubt so. Give your instances - even when used only once - a name that describes what their intention - the idea behind - is. Don´t make it hard for others to understand your code by cryptifying it.
Apart from this you can restrict the use of your class to be private by nesting it within another one:
public class MyClass
{
private class Strings { /* ... */ }
}
Now your class is just visible to itself and within MyClass (and in other classes that are nested in MyClass of course). This makes it impossible to access the class from the outside like so:
var strings = new MyClass.Strings();
Try making the inner class static. That way you will be able to use the syntax you describe:
class MyClass {
public static Strings {
public static string string1;
public static string string2;
public static void MyMethod() {}
}
}
You can then call: MyClass.Strings.string1 = "Hell, world!";
I am converting some java code C# for use in my MonoDroid application. I have some snippets where interfaces are declared and then initialized in to objects. I am not 100% sure on the best approach to implement these in to C#.
For example:
public class NumberPicker {
public interface Formatter {
String toString(int value);
}
public static final NumberPicker.Formatter TWO_DIGIT_FORMATTER =
new NumberPicker.Formatter() {
//some code here
};
}
What would be the equivalent or best approach to do this in c#?
for simple "single-use" interfaces with one function (like event listeners, for example), you could think of rewriting the code to use delegates and anonymous functions instead.
delegate String Formatter(int n);
...
Formatter TWO_DIGIT_FORMATTER = delegate(int n) {
//code here
};
you can then use TWO_DIGIT_FORMATTER like a function ( TWO_DIGIT_FORMATTER(12) ).
Anonymous classes (which is what's happening in your java code) don't exist in C#, but delegates suffice in cases like this.
You would have to create a class that implements the Formatter interface and then create an instance of that.
i.e.
public class MyFormatter : IFormatter
{
public string ToString(int value)
{
//implementation
}
}
Then create an instance of MyFormatter with the new operator.
public static IFormatter TWO_DIGIT_FORMATTER = new MyFormatter ();
The 'I' prefix for interfaces is something done in the .net world but it isn't required, just convention.
So the easiest way I have found to handle this situation is to create a private nested class within your main class and then have it inherit from as many interfaces as you need. Such as IOnClickListener, IOnMouseDownListener, and then declare it at the top of your class and reuse it over and over wherever needed. Makes it much easier... If you have interfaces that repeat or have the same method names you can declare them explicitly, for example
IOnClickListener.OnClick(object sender, EventArgs)
{
}
Just as an example, you would obviously want to use the real method names and interface names. Also don't forget to dispose of the instance in your OnDestroy.
Why is static virtual impossible? Is C# dependent or just don't have any sense in the OO world?
I know the concept has already been underlined but I did not find a simple answer to the previous question.
virtual means the method called will be chosen at run-time, depending on the dynamic type of the object. static means no object is necessary to call the method.
How do you propose to do both in the same method?
Eric Lippert has a blog post about this, and as usual with his posts, he covers the subject in great depth:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/calling-static-methods-on-type-parameters-is-illegal-part-one
“virtual” and “static” are opposites! “virtual” means “determine the method to be called based on run time type information”, and “static” means “determine the method to be called solely based on compile time static analysis”
The contradiction between "static" and "virtual" is only a C# problem. If "static" were replaced by "class level", like in many other languages, no one would be blindfolded.
Too bad the choice of words made C# crippled in this respect. It is still possible to call the Type.InvokeMember method to simulate a call to a class level, virtual method. You just have to pass the method name as a string. No compile time check, no strong typing and no control that subclasses implement the method.
Some Delphi beauty:
type
TFormClass = class of TForm;
var
formClass: TFormClass;
myForm: TForm;
begin
...
formClass = GetAnyFormClassYouWouldLike;
myForm = formClass.Create(nil);
myForm.Show;
end
Guys who say that there is no sense in static virtual methods - if you don't understand how this could be possible, it does not mean that it is impossible. There are languages that allow this!! Look at Delphi, for example.
I'm going to be the one who naysays. What you are describing is not technically part of the language. Sorry. But it is possible to simulate it within the language.
Let's consider what you're asking for - you want a collection of methods that aren't attached to any particular object that can all be easily callable and replaceable at run time or compile time.
To me that sounds like what you really want is a singleton object with delegated methods.
Let's put together an example:
public interface ICurrencyWriter {
string Write(int i);
string Write(float f);
}
public class DelegatedCurrencyWriter : ICurrencyWriter {
public DelegatedCurrencyWriter()
{
IntWriter = i => i.ToString();
FloatWriter = f => f.ToString();
}
public string Write(int i) { return IntWriter(i); }
public string Write(float f) { return FloatWriter(f); }
public Func<int, string> IntWriter { get; set; }
public Func<float, string> FloatWriter { get; set; }
}
public class SingletonCurrencyWriter {
public static DelegatedCurrencyWriter Writer {
get {
if (_writer == null)
_writer = new DelegatedCurrencyWriter();
return _writer;
}
}
}
in use:
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400.0
SingletonCurrencyWriter.Writer.FloatWriter = f => String.Format("{0} bucks and {1} little pennies.", (int)f, (int)(f * 100));
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400 bucks and 0 little pennies
Given all this, we now have a singleton class that writes out currency values and I can change the behavior of it. I've basically defined the behavior convention at compile time and can now change the behavior at either compile time (in the constructor) or run time, which is, I believe the effect you're trying to get. If you want inheritance of behavior, you can do that to by implementing back chaining (ie, have the new method call the previous one).
That said, I don't especially recommend the example code above. For one, it isn't thread safe and there really isn't a lot in place to keep life sane. Global dependence on this kind of structure means global instability. This is one of the many ways that changeable behavior was implemented in the dim dark days of C: structs of function pointers, and in this case a single global struct.
Yes it is possible.
The most wanted use case for that is to have factories which can be "overriden"
In order to do this, you will have to rely on generic type parameters using the F-bounded polymorphism.
Example 1
Let's take a factory example:
class A: { public static A Create(int number) { return ... ;} }
class B: A { /* How to override the static Create method to return B? */}
You also want createB to be accessible and returning B objects in the B class. Or you might like A's static functions to be a library that should be extensible by B. Solution:
class A<T> where T: A<T> { public static T Create(int number) { return ...; } }
class B: A<B> { /* no create function */ }
B theb = B.Create(2); // Perfectly fine.
A thea = A.Create(0); // Here as well
Example 2 (advanced):
Let's define a static function to multiply matrices of values.
public abstract class Value<T> where T : Value<T> {
//This method is static but by subclassing T we can use virtual methods.
public static Matrix<T> MultiplyMatrix(Matrix<T> m1, Matrix<T> m2) {
return // Code to multiply two matrices using add and multiply;
}
public abstract T multiply(T other);
public abstract T add(T other);
public abstract T opposed();
public T minus(T other) {
return this.add(other.opposed());
}
}
// Abstract override
public abstract class Number<T> : Value<T> where T: Number<T> {
protected double real;
/// Note: The use of MultiplyMatrix returns a Matrix of Number here.
public Matrix<T> timesVector(List<T> vector) {
return MultiplyMatrix(new Matrix<T>() {this as T}, new Matrix<T>(vector));
}
}
public class ComplexNumber : Number<ComplexNumber> {
protected double imag;
/// Note: The use of MultiplyMatrix returns a Matrix of ComplexNumber here.
}
Now you can also use the static MultiplyMatrix method to return a matrix of complex numbers directly from ComplexNumber
Matrix<ComplexNumber> result = ComplexNumber.MultiplyMatrix(matrix1, matrix2);
While technically it's not possible to define a static virtual method, for all the reasons already pointed out here, you can functionally accomplish what I think you're trying using C# extension methods.
From Microsoft Docs:
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Check out Extension Methods (C# Programming Guide) for more details.
In .NET, virtual method dispatch is (roughly) done by looking at the actual type of an object when the method is called at runtime, and finding the most overriding method from the class's vtable. When calling on a static class, there is no object instance to check, and so no vtable to do the lookup on.
To summarize all the options presented:
This is not a part of C# because in it, static means "not bound to anything at runtime" as it has ever since C (and maybe earlier). static entities are bound to the declaring type (thus are able to access its other static entities), but only at compile time.
This is possible in other languages where a static equivalent (if needed at all) means "bound to a type object at runtime" instead. Examples include Delphi, Python, PHP.
This can be emulated in a number of ways which can be classified as:
Use runtime binding
Static methods with a singleton object or lookalike
Virtual method that returns the same for all instances
Redefined in a derived type to return a different result (constant or derived from static members of the redefining type)
Retrieves the type object from the instance
Use compile-time binding
Use a template that modifies the code for each derived type to access the same-named entities of that type, e.g. with the CRTP
The 2022+ answer, if you are running .Net 7 or above, is that now static virtual members is now supported in interfaces. Technically it's static abstract instead of "static virtual" but the effect is that same. Standard static methods signatures can be defined in an interface and implemented statically.
Here are a few examples on the usage and syntax in .Net 7
I am reading Josh Bloch's book Effective Java and he suggests using a builder design pattern when building objects that have large amounts of members. From what I can see it isn't the vanilla design pattern but looks like his variation. I rather like the look of it and was trying to use it in a C# web application that I am writting. This is the code written in Java and works perfectly
public class Property {
private String title;
private String area;
private int sleeps = 0;
public static void main(String[] args) {
Property newProperty = new Property.Builder("Test Property").Area("Test Area").Sleeps(7).build();
}
private Property(Builder builder) {
this.title = builder.title;
this.area = builder.area;
this.sleeps =builder.sleeps;
}
public static class Builder{
private String title;
private String area;
private int sleeps = 0;
public Builder (String title){
this.title = title;
}
public Builder Area(String area){
this.area = area;
return this;
}
public Builder Sleeps(int sleeps){
this.sleeps = sleeps;
return this;
}
public Property build() {
return new Property(this);
}
}
}
When I put this into what I think is the C# equivalent
public class Property
{
private String title;
private String area;
private Property(Builder Builder)
{
title = Builder.title;
area = Builder.area;
}
public static class Builder
{
// Required parameters
private String title;
private String area;
// Optional parameters
private int sleeps = 0;
public Builder(String val)
{
this.title = val;
}
public Builder Area(String val)
{
this.area = val;
return this;
}
public Builder Sleeps(int val)
{
this.sleeps = val;
return this;
}
public Property build()
{
return new Property(this);
}
}
}
Then I get compiler warnings. Most of them "cannot declare instance members in a static class".
So my question is firstly what have I missed? If I have missed something, can I do it in the manner Josh Bloch recommends but in C#, and lastly, and this one important too, is this thread-safe?
public static class in Java means that you define a static nested class. That means that it is logically contained in another class but instances of it can exist without a reference to it's outer class. A non-static nested class is called an "inner class" and instances of it can only ever exist in relation to an instance of the outer class.
In C# a static class is one that can't be instantiated and thus can't have any non-static members. There is no direct language-level equivalent to this construct in Java, but you can easily prevent instantiation of a Java class by providing only a private constructor.
Short Java recap:
All Classes defined inside another Class are "nested Classes"
nested Classes that are not static are called inner Classes
instances of inner Classes can only exist in relation to an instance of the outer Class
static nested Classes have no separate name
static nested Classes are largely independent from their outer class (except for some privileged access).
I'd be happy if some C# guru told us how inner/nested classes are handled in C#/.NET.
I think you can achieve pretty much the same effect if you create Builder as a top level class ( for that's exactly what it is in Java ) and create a factory method to receive the builder in order to keep the constructor private ( which in turn would let you return subclasses instances if needed).
The point is to let the builder perform the steps needed to create the object.
So ( without knowing much about C# you could try something like this )
// My naive C# attempt:P
public class Property
{
public static void main( String []args )
{
Property p = Property.buildFrom( new Builder("title").Area("area").Etc() )
}
public static Property buildFrom( Builder builder )
{
return new Propert( builder );
}
private Property ( Builder builder )
{
this.area = builder.area;
this.title = builder.title;
// etc.
}
}
public class Builder
{
public Builder ( String t )
{
this.title = t;
}
public Builder Area( String area )
{
this.area = area;
return this;
}
// etc.
}
The whole point of having Builder as an static inner class of property is to create a high coupling among the two ( as if they where one ). That's why build method in Builder calls the private "Property" constructor.
Probably in C# you could use an alternate artifact to create the same coupling.
saua has the right answer, but I would like to be clear about your example in particular:
In the C# version, you should remove the static keyword from the inner class. It doesn't mean the same thing as the Java version, and indeed the effect it has in the Java version is the normal behaviour for inner classes in C#.
In Java a nested class is by default associated with a particular instance of its containing class. An instance of the nested class can access variables and methods of the containing instance. If the nested class has the "static" keyword then it is not associated with an instance of the outer class. It is in this sense that Bloch uses the "static" keyword on the Builder class.
"Static" means something different when applied to a nested class in C#. I don't know what keyword you would use in C#, or even if it is necessary. Did you try leaving the static keyword out of the class definitions?
Use of "static" in Java class definitions is discussed in Item 18 of Effective Java.
I'm not sure what Java is doing with the static class declaration, but in C#, a static class is one that only has class-level members and, by definition, can not be implemented into an instance. It's like the old VB difference between Class and Module.
I don't know why C# is complaining, but I can say that the code is thread-safe. If you were creating two or more instances of Property at the same time, each in their own threads, you wouldn't run into any problems.
I will try removing the static keyword. My other thought was, as others have already suggested, was to create the builder class as a top level class.
To answer several comments about how to get Java's inner class behavior in C#, it would seem that the reference to the enclosing class needs to be passed in the constructor of the inner class (from a quick Google - C# may have since added the capability).
public class Outer
{
...
void SomeMethod() {
Inner workerBee=new Inner(this);
}
...
class Inner
private Outer outer;
{
Inner(Outer out) {
outer=out;
}
}
}
So C# just makes explicit what Java did implicitly, including explicitly needing the reference to access members of the outer class.
Personally, I have never liked the Java implicit accesses to the outer classes members, since it seems too easy to trip up and accidently break encapsulation - I nearly always create my inner classes as static and pass them a reference to the outer class.
Assuming that your class has publicly settable properties corresponding to the builder members, you don't need Bloch's builder pattern in C#. You can use Object Initializers:
public class Property
{
public String Title {get; set};
public String Area {get; set};
public int Sleeps {get; set};
public static void main(String[] args)
{
Property newProperty = new Property {Title="Test Property", Area="Test Area", Sleeps=7};
}
}
This won't be possible if you need more encapsulation.