I'm trying to recreate this in C#.
The problem i get is if i use constructors i MUST use new MyInt which i DO NOT WANT (to verbose). The way around it is to use the implicit/explicit operators. However they MUST be public... How the heck do i implement this in feature in C#?
The short question is i'd like to pass byte/short into a function but not int. Passing int should get me a compile error. I know i can easily get runtime with a public implicit int operator. The code below shows that int is automatically converted to char
Running sample shows true
using System;
class Program
{
public static void Write(MyInt v)
{
Console.WriteLine("{0}", v.v is byte);
}
static void Main(string[] args)
{
Write(2);
}
}
public struct MyInt
{
public object v;
public MyInt(byte vv) { v = vv; }
public MyInt(short vv) { v = vv; }
public MyInt(byte[] vv) { v = vv; }
public static implicit operator MyInt(byte vv) { return new MyInt { v = vv }; }
//public static extern implicit operator MyInt(int vv);
}
Heres more code which is useless. It implements MyInt2/MyInt which isn't required in the C++ solution
Just declare that your function takes short. Byte would be implicitly converted to short, but there is no implicit conversion from int to short, so int just won't pass
public class Class1
{
public static void Aaa(short a)
{
}
public void Bbb()
{
int i = 5;
byte b = 1;
short c = 1;
Class1.Aaa(i); // Gives error
Class1.Aaa(b); // Ok
Class1.Aaa(c); // ok
}
}
Related
This is the Question I am trying to solve in C Sharp.
I am getting an error:
Error Expected ; or = (cannot specify constructor arguments in declaration)
Can anyone help me to solve this or guide me to solve this?
namespace program
{
public class Integer
{
private int intvar;
public Integer()
{
intvar = 0;
}
public Integer(int x)
{
intvar = x;
}
public void display()
{
Console.Write(intvar);
Console.Write("\n");
}
public void add(Integer x, Integer y)
{
intvar = x.intvar + y.intvar;
}
}
class Program
{
static void Main(string[] args)
{
Integer a(5),b(45);
Integer c;
c.add(a,b);
c.display();
Console.ReadLine();
}
}
}
You cannot create objects like that in C#. Im assuming you come from C++ where this syntax is possible.
In C# you have to create objects using new:
Integer foo = new Integer(45);
To create a new instance of a type, you have to invoke one of the constructors of that type using the new operator. For example:
class Program
{
static void Main(string[] args)
{
var a = new Integer(5);
var b = new Integer(45);
var c = new Integer(); //result instance
c.add(a, b);
c.display();
Console.ReadLine();
}
}
I have two constructors which feed values to readonly fields.
public class Sample
{
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
_intField = i;
}
public Sample(int theInt) => _intField = theInt;
public int IntProperty => _intField;
private readonly int _intField;
}
One constructor receives the values directly, and the other does some calculation and obtains the values, then sets the fields.
Now here's the catch:
I don't want to duplicate the
setting code. In this case, just one
field is set but of course there may
well be more than one.
To make the fields readonly, I need
to set them from the constructor, so
I can't "extract" the shared code to
a utility function.
I don't know how to call one
constructor from another.
Any ideas?
Like this:
public Sample(string str) : this(int.Parse(str)) { }
If what you want can't be achieved satisfactorily without having the initialization in its own method (e.g. because you want to do too much before the initialization code, or wrap it in a try-finally, or whatever) you can have any or all constructors pass the readonly variables by reference to an initialization routine, which will then be able to manipulate them at will.
public class Sample
{
private readonly int _intField;
public int IntProperty => _intField;
private void setupStuff(ref int intField, int newValue) => intField = newValue;
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
setupStuff(ref _intField,i);
}
public Sample(int theInt) => setupStuff(ref _intField, theInt);
}
Before the body of the constructor, use either:
: base (parameters)
: this (parameters)
Example:
public class People: User
{
public People (int EmpID) : base (EmpID)
{
// Add more statements here.
}
}
I am improving upon supercat's answer. I guess the following can also be done:
class Sample
{
private readonly int _intField;
public int IntProperty
{
get { return _intField; }
}
void setupStuff(ref int intField, int newValue)
{
//Do some stuff here based upon the necessary initialized variables.
intField = newValue;
}
public Sample(string theIntAsString, bool? doStuff = true)
{
//Initialization of some necessary variables.
//==========================================
int i = int.Parse(theIntAsString);
// ................
// .......................
//==========================================
if (!doStuff.HasValue || doStuff.Value == true)
setupStuff(ref _intField,i);
}
public Sample(int theInt): this(theInt, false) //"false" param to avoid setupStuff() being called two times
{
setupStuff(ref _intField, theInt);
}
}
Here is an example that calls another constructor, then checks on the property it has set.
public SomeClass(int i)
{
I = i;
}
public SomeClass(SomeOtherClass soc)
: this(soc.J)
{
if (I==0)
{
I = DoSomethingHere();
}
}
Yeah, you can call other method before of the call base or this!
public class MyException : Exception
{
public MyException(int number) : base(ConvertToString(number))
{
}
private static string ConvertToString(int number)
{
return number.toString()
}
}
Constructor chaining i.e you can use "Base" for Is a relationship and "This" you can use for same class, when you want call multiple Constructor in single call.
class BaseClass
{
public BaseClass():this(10)
{
}
public BaseClass(int val)
{
}
}
class Program
{
static void Main(string[] args)
{
new BaseClass();
ReadLine();
}
}
When you inherit a class from a base class, you can invoke the base class constructor by instantiating the derived class
class sample
{
public int x;
public sample(int value)
{
x = value;
}
}
class der : sample
{
public int a;
public int b;
public der(int value1,int value2) : base(50)
{
a = value1;
b = value2;
}
}
class run
{
public static void Main(string[] args)
{
der obj = new der(10,20);
System.Console.WriteLine(obj.x);
System.Console.WriteLine(obj.a);
System.Console.WriteLine(obj.b);
}
}
Output of the sample program is
50 10 20
You can also use this keyword to invoke a constructor from another constructor
class sample
{
public int x;
public sample(int value)
{
x = value;
}
public sample(sample obj) : this(obj.x)
{
}
}
class run
{
public static void Main(string[] args)
{
sample s = new sample(20);
sample ss = new sample(s);
System.Console.WriteLine(ss.x);
}
}
The output of this sample program is
20
Error handling and making your code reusable is key. I added string to int validation and it is possible to add other types if needed. Solving this problem with a more reusable solution could be this:
public class Sample
{
public Sample(object inputToInt)
{
_intField = objectToInt(inputToInt);
}
public int IntProperty => _intField;
private readonly int _intField;
}
public static int objectToInt(object inputToInt)
{
switch (inputToInt)
{
case int inputInt:
return inputInt;
break;
case string inputString:
if (!int.TryParse(inputString, out int parsedInt))
{
throw new InvalidParameterException($"The input {inputString} could not be parsed to int");
}
return parsedInt;
default:
throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");
break;
}
}
Please, please, and pretty please do not try this at home, or work, or anywhere really.
This is a way solve to a very very specific problem, and I hope you will not have that.
I'm posting this since it is technically an answer, and another perspective to look at it.
I repeat, do not use it under any condition. Code is to run with LINQPad.
void Main()
{
(new A(1)).Dump();
(new B(2, -1)).Dump();
var b2 = new B(2, -1);
b2.Increment();
b2.Dump();
}
class A
{
public readonly int I = 0;
public A(int i)
{
I = i;
}
}
class B: A
{
public int J;
public B(int i, int j): base(i)
{
J = j;
}
public B(int i, bool wtf): base(i)
{
}
public void Increment()
{
int i = I + 1;
var t = typeof(B).BaseType;
var ctor = t.GetConstructors().First();
ctor.Invoke(this, new object[] { i });
}
}
Since constructor is a method, you can call it with reflection. Now you either think with portals, or visualize a picture of a can of worms. sorry about this.
In my case, I had a main constructor that used an OracleDataReader as an argument, but I wanted to use different query to create the instance:
I had this code:
public Subscriber(OracleDataReader contractReader)
{
this.contract = Convert.ToString(contractReader["contract"]);
this.customerGroup = Convert.ToString(contractReader["customerGroup"]);
this.subGroup = Convert.ToString(contractReader["customerSubGroup"]);
this.pricingPlan= Convert.ToString(contractReader["pricingPlan"]);
this.items = new Dictionary<string, Member>();
this.status = 0;
}
So I created the following constructor:
public Subscriber(string contract, string customerGroup) : this(getSubReader(contract, customerGroup))
{ }
and this method:
private static OracleDataReader getSubReader(string contract, string customerGroup)
{
cmdSubscriber.Parameters[":contract"].Value = contract + "%";
cmdSubscriber.Parameters[":customerGroup"].Value = customerGroup+ "%";
return cmdSubscriber.ExecuteReader();
}
notes: a statically defined cmdSubscriber is defined elsewhere in the code; My main constructor has been simplified for this illustration.
In case you need to run something before calling another constructor not after.
public class Sample
{
static int preprocess(string theIntAsString)
{
return preprocess(int.Parse(theIntAsString));
}
static int preprocess(int theIntNeedRounding)
{
return theIntNeedRounding/100;
}
public Sample(string theIntAsString)
{
_intField = preprocess(theIntAsString)
}
public Sample(int theIntNeedRounding)
{
_intField = preprocess(theIntNeedRounding)
}
public int IntProperty => _intField;
private readonly int _intField;
}
And ValueTuple can be very helpful if you need to set more than one field.
NOTE: most of the solutions above does not work for structs.
Unfortunately initializing struct fields in a method called by a constructor is not recognized by the compiler and will lead to 2 errors:
in the constructor: Field xxxx must be fully assigned...
in the method, if you have readonly fields: a read-only field cannot be assigned except in a constructor.
These can be really frustrating for example when you just need to do simple check to decide on which constructor to orient your call to.
I'm used to programming in Java however for this project I'm supposed to be using C#, I'm trying to convert my Packet system over from my Java project, however I'm running into some issues using the C# Compiler. Here's the code.
abstract class Packet
{
public static enum PacketTypes
{
INVALID(-1), LOGIN(00);
private int packetId;
private PacketTypes(int packetId)
{
this.packetId = packetId;
}
public int getId() { return packetId; }
}
}
This is actually exactly how it's done in my Java Code, and I have the individual packets extend the Packet class. I'm trying to figure out how to make this all come together in C#. Perhaps having a separate class for each packet isn't the way it should be done here?
I'm not sure what you're trying to achieve, but you can set values for particular enum elements in C#:
public enum PacketTypes
{
INVALID = -1;
LOGIN = 0;
}
Because enum is by default backed by int, you can cast it from/to int without additional code.
enums in C# cannot content any members, so you can't add methods/properties/fields to enum declaration.
Unlike Java where enums are classes, in C# enums are plain values. They cannot have member functions or fields.
One approach that could help is to define an extension method for your enum, like this:
public static class PacketTypesExtensions {
static readonly IDictionary<PacketTypes,int> IdForType = new Dictionary<PacketTypes,int> {
{ PacketTypes.INVALID, -1 }
, { PacketTypes.LOGIN, 0 }
};
static readonly IDictionary<PacketTypes,string> DescrForType = new Dictionary<PacketTypes,string> {
{ PacketTypes.INVALID, "<invalid packet type>" }
, { PacketTypes.LOGIN, "<user login>" }
};
public static string Description(this PacketTypes t) {
return DescrForType[t];
}
public static int Id(this PacketTypes t) {
return IdForType[t];
}
}
This lets you keep Java syntax:
PacketTypes pt = ... // <<== Assign a packet type here
int id = pt.Id(); // This calls the static extension method
string d = pt.Description();
You could try this in addition to Marcins answer.
public enum PacketTypes
{
INVALID = -1;
LOGIN = 0;
}
public class Packet
{
public PacketTypes PacketType { get; set;}
}
In your code somewhere, you would do this
public void DoSomething()
{
var packet = new Packet();
packet.PacketType = PacketTypes.INVALID; // Assign packtype
Console.WriteLine(packet.PacketType.ToString()); // Retrieve and print
}
In C I can do
void foo() {
static int c = 0;
printf("%d,", c);
c ++;
}
foo();
foo();
foo();
foo();
it should print 0,1,2,3
Is there an equivalent in C#?
While some have suggested as static member variable, this is not the same due to visibility. As an alternative to the answer by aquinas, if closures are accepted, then this can be done:
(Note that Foo is a a property and not a method and that c is "per instance".)
class F {
public readonly Action Foo;
public F () {
int c = 0; // closured
Foo = () => {
Console.WriteLine(c);
c++;
};
}
}
var f = new F();
f.Foo(); // 0
f.Foo(); // 1
However, C# has no direct equivalent to a static variable in C.
Happy coding.
Something like:
class C
{
private static int c = 0;
public void foo()
{
Console.WriteLine(c);
c++;
}
}
No there is no way to achieve the same behaviour as the static c function variable ...
There are no globals in C#, however, you can create a static field within your class.
public class Foo{
private static int c = 0;
void Bar(){
Console.WriteLine(c++);
}
}
You can't do it at a method level. The closest you can do at a method level is something like this, and this isn't really that close. In particular, it only works if you have a reference to the enumerator. If someone else calls this method, they won't see your changes.
class Program {
static IEnumerable<int> Foo() {
int c = 0;
while (true) {
c++;
yield return c;
}
}
static void Main(string[] args) {
var x = Foo().GetEnumerator();
Console.WriteLine(x.Current); //0
x.MoveNext();
Console.WriteLine(x.Current); //1
x.MoveNext();
Console.WriteLine(x.Current); //2
Console.ReadLine();
}
}
What interesting is that VB.NET does support static local variables: http://weblogs.asp.net/psteele/pages/7717.aspx. As this page notes, .NET itself doesn't support this, but the VB.NET compiler fakes it by adding a static class level variable.
I have a .Net library. say with 2 public functions. say one is Summmator which takes 2 arguments and does A+B. Another function simpleMultiplicator which takes 2 arguments: a number to multiplicate and count of times it should be multiplicated. A simpleMultiplicator function when called uses Summmator function. So it is my library. It is compiled into dll for .net4. In my programm I want to extend or modify Summator function so that when I call simpleMultiplicator it would use my modification of original Summator function. Is it possible in .net4, how to do it?
(C#, visual-C++)
It depends on how you design your classes. You state that your library exports two public functions, but they need to be defined on a class either as static or instance method, so you can make use of object-orientated principles like inheritance or polymorphism to achieve what you want.
Here is an example using inheritance:
namespace MyLibrary
{
public class MyMath
{
// Be aware of the virtual keyword which enables overriding the method
public virtual int Summmator(int a, int b)
{
return a + b;
}
public int SimpleMultiplicator(int a, int b)
{
int result = 0;
for (int i = 0; i < b; i++)
{
result = Summmator(result, a);
}
}
}
}
namespace MyProgram
{
using MyLibrary;
public class MyExtendedMath : MyMath
{
public override int Summmator(int a, int b)
{
return a + 2 * b;
}
}
public static class Program
{
public static void Main()
{
MyMath math = new MyExtendedMath();
int result = math.SimpleMultiplicator(2, 3);
Console.WriteLine(result);
}
}
}
Another way is to use polymorphism:
namespace MyLibrary
{
public interface ISummmator
{
int Summmator(int a, int b);
}
public class Summmator : ISummator
{
public int Summmator(int a, int b)
{
return a + b;
}
}
public static class MyMath
{
public static int SimpleMultiplicator(int a, int b, ISummmator summmator)
{
int result = 0;
for (int i = 0; i < b; i++)
{
result = summmator.Summmator(result, a);
}
}
}
}
namespace MyProgram
{
using MyLibrary;
public class MySummmator : ISummmator
{
public int Summmator(int a, int b)
{
return a + 2 * b;
}
}
public static class Program
{
public static void Main()
{
int result = MyMath.SimpleMultiplicator(2, 3, new MySummmator());
Console.WriteLine(result);
}
}
}
Best Regards,
Oliver Hanappi
First, I'd objectify these things. So you have a Summator which provides a sum function, and a SimpleMultiplicator which provides a multiply function. Then, you add the Summator to the SimpleMultiplicator in the default case. For example,
class SimpleMultiplicator
{
public SimpleMultiplicator()
{
this.summator = new Summator();
}
public int Mult(int a, int b)
{
// ...
this.summator.sum(something, somethingelse);
// etc
}
Then you create another constructor where you can override the default Summator:
public SimpleMultiplicator(Summator summator)
{
this.summator = summator;
}
So if you want to change the summation function, you create a new Summator-based class, override its sum() method and pass it on to the SimpleMultiplicator constructur.