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 an assembly Test.Dll I have a C# class:
public class MyClass : IDisposable
{
int _TheInt;
public MyClass (int i) {_TheInt = i;}
public int GetInt() { return _TheInt;}
}
and a function:
public int MyFunc(MyClass myObject) { return myObject.GetInt(); }
How, in an ironPython script, create an object of type MyClass and call MyFunc with this object?
I can do the first step but as I am not an expert in neither C# and Python I failed for the second step.
Any help would be highly appreciated.
First, you need to import dll:
import clr
clr.AddReferenceToFileAndPath(r"/path/to/Test.dll")
then after reference was added, you can import your C# namespace or class, and create the object:
import MyNameSpace.MyClass # namespace name class from C# DLL
obj = MyClass(1)
# Now you have an object, let's call the methods:
myIntValue = obj.GetInt()
Then, if you want to call MyFunc, instead of direct call of GetInt(), you need to make it static (since it accepts object as argument
//Put that inside MyClass declaration, cause global functions are not allowed by C#
public static int MyFunc(MyClass myObject) { return myObject.GetInt(); }
And call it on python's side:
result = MyClass.MyFunc(obj)
Recently, I received a bug report from a VB.Net user about a strange overload resolution failure when upgrading to a newer version of OpenTK: Error 1 'Uniform3' is ambiguous because multiple kinds of members with this name exist in class 'OpenTK.Graphics.OpenGL.GL'
Why is this strange? Because the overloads in question are identical between the old and the newer versions of the library!
Some testing later, I managed to isolate the problem in a small test case:
// C# library - this one works
namespace Test
{
public partial class GL
{
public static void Foo(float bar) { }
}
public partial class GL
{
public static void Foo(int bar) { }
public static void Foo(ref int bar) { }
}
}
The above code can be consumed by VB.Net without an issue. However, if I re-order the two partial classes:
// C# library - this one fails
namespace Test
{
public partial class GL
{
public static void Foo(int bar) { }
public static void Foo(ref int bar) { }
}
public partial class GL
{
public static void Foo(float bar) { }
}
}
I get a failure!
The VB.Net code looks like this:
REM VB.Net code that consumes the C# library
Module Module1
Sub Main()
Test.GL.Foo(0)
End Sub
End Module
What is going on here?! Why does the order of the two partial classes matter?
More importantly, is there a better solution than reordering the C# code files and hope the compiler consumes them one way but not the other? (For instance, is there some attribute I can apply to remove one of the overloads from consideration during overload resolution in VB.Net?)
I worked around this issue by changing the order in which the overloads appear inside the compiled binary. This is awful in many different ways, but it appears to work well enough for now.
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 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.