I'm new to programming and I have the following problem.
I have a class with with an Array. However, I only know what size the array will have at a later point.
public class MyData
{
public double[] rad;
public void Integrate(int h_start, int h_stop, double dla_tar)
{
rad = new double[Math.Abs(h_stop - h_start)];
...fill up the rad array
}
--work with rad here--
}
How can I get the function Integrate to create the rad array in the MyData class. Like that it always stays null. This is probably a very dumb question...
The key is to call Integrate before using rad. As long as you don't use rad in any way until you initialize it, you will be fine.
Any field in a C# class automatically starts out as the default value for that type, which is 0 for a numeric type (int, uint, long, etc.), false for a bool, and null for any reference type, including arrays. The canonical way to solve this problem is to initialize the data from the constructor. So you could do something like
public class MyData
{
public double[] rad
{
get;
private set;
}
public MyData(int start, int stop, double tar)
{
rad = new double[Math.Abs(start - stop)];
// More code here
}
// No need for an integrate method now - the work is done in the constructor
}
This way, it's impossible to use rad before it's initialized.
If you find that moving the initialization code to the constructor doesn't make sense, you probably need to refactor into two classes so that each class has one job.
Related
I started to learn about C# and I usually use C++.
There is a bunch of things that I'm trying to adapt, but std::array seem like impossible...
I just want to run this kind of code:
public struct Foo {};
public struct Test
{
public Foo value[20];
};
I don't want to allocate each time I use this struct and I don't want to use a class ever...
I saw fixed keyword but it works only for basic types...
There is not equivalent to something as simple as std::array?
I can even do that in C.
How would you sove this problem? (Even if it's still dynamically alocated..)
Using a fixed size buffer (fixed) is only possible for primitive types since its use is intended for interop. Array types are reference types, and so they can have dynamic size:
public struct Test
{
public Foo[] value;
}
Note however that copying the struct will only copy the reference, so the arrays will be identical. I suggest you either make the type immutable (by disabling writing to the array), or change struct to class and control cloning explicitly.
There is no such thing as a fixed size by-value array type in C# (although I have proposed it once). The closest thing you can get to it is a value tuple.
So it seems like there is no way to not do something as stupid as dynamically allocate something know at compile time. But that's C# so I just need to... try to close my eyes.
Anyway I did something to solve array alias and fixed array at the same time (I didn't ask about array alias on this question thought).
public abstract
class Array<T>
{
private T[] data;
protected Array(int size) { data = new T[size]; }
public T this[int i]
{
get { return data[i]; }
set { data[i] = value; }
}
};
public Alias : Array<int>
{
static public int Length = 10;
public Area() : base(Length) {}
};
And some people say it's quicker to write code with C#...
If someone have better I'll glady take it!
I am creating a simple text-game. My Character struct keeps resetting it Can value. What am I doing wrong and how do I fix it? Here is the code:
namespace MyNamespace
{
struct Character
{
public float Can;
//...
}
class MainClass
{
public static void Move (Character a)
{
bool cal = true;
while (cal)
{
Thread.Sleep(500);
if(a.Can <= 100)
{
a.Can += 1;
}
else
{
cal = false;
}
}
}
}
//...
}
A struct is a value type. When you pass it to a method or assign it to another variable, data are copied. You will then operate on a copy.
Consider your method call Dinlen (oyuncu);. It copies the Karakter oyuncu, and then changes the field Can of the copy.
Consider using reference types (class) instead. If you use a struct, consider making it an immutable type. Read the thread Why are mutable structs evil?
If you want to pass a struct to a method for the purpose of having that method modify it, the method must use a ref qualifier on the parameter. If you pass a struct to a method without a ref parameter, there is no way that the method can modify any fields of that struct.
Note that some people may suggest replacing the struct with a class so that one won't have to use the ref qualifier. That is a dangerous notion, since every method receiving a reference to a mutable class object will be free to cause the object to be mutated at any time thereafter. There's no clean way to pass a reference to a mutable class object without allowing the recipient to mutate it, nor is there any way to be certain that code which is given a class-object reference won't persist it and use it to modify the object at any arbitrary future time. Structures don't have either of these problems.
If an object holds a value-type field e.g. MyBounds of type Drawing.Rectangle, and I call Foo(MyBounds) I can be assured that there is no possibility that Foo will change MyBounds. Further, if I call Bar(ref MyBounds) I can expect that Bar might change MyBounds, but all changes will be complete before the method returns. If Rectangle had been a mutable class type, then without examining Foo and Bar I would have no way of knowing whether the properties of MyBounds might be changed at any arbitrary time in the future.
Someone who doesn't understand that structs are different from classes may be confused by the way structs behave, but all structs with exposed public fields behave the same way, so if one understands how one such struct works, one will understand them all. There is one evil aspect of structures, which is that instance methods and properties defined on a struct will receive this as a ref parameter, but if one attempts to do something like:
readonly System.Drawing.Rectangle myRect = whatever;
...
myRect.Offset(4,2);
the system will recognize that myRect cannot be passed as a ref parameter (since it's read-only) and will, without any diagnostic, change the code to:
readonly System.Drawing.Rectangle myRect = whatever;
...
System.Drawing.Rectangle temp = myRect;
temp.Offset(4,2);
What is evil there, however, is not the fact that Rectangle is mutable, but rather the fact that the compiler assumes the above code substitution is legitimate when calling any and all value-type methods. Unless or until Microsoft gets around to adding an attribute to indicate that calling a particular method on a read-only structure should result in an error rather than performing such substitution, the only safe way to code struct methods that operate on a structure "in-place" would be to use a format like: static void Offset(ref Rectangle it, int x, int y);, in which case Rectangle.Offset(ref myRect, 4, 2); would fail as it should.
I believe the problem is you are passing the struct as a variable into your first method, but struct's are value types - i.e. they are copied, not passed by reference.
Changing your struct to class will have the behaviour you require.
P.S. Is there a reason you chose a struct? They are normally used for more advanced scenarios, where the developer knows more about the benefits and flaws of using this type.
When you are passing struct instance into method, a copy of struct is created (it is passed by value). Any changes to struct inside method does not affect original struct which you passed.
Solutions? Use class instead of struct. Instances of classes passed by reference. Well you can pass structs by reference, but why would you trying to use structs like classes? Use classes instead.
class Karakter
{
public string Isim { get; set; }
public float Can { get; set; }
public int Seviye { get; set; }
public int Exp { get; set; }
public float Guc { get; set; }
public string Irk { get; set; }
public int vExp { get; set; }
public override string ToString()
{
return String.Format("Adınız:{0}\nIrkınız:{1}\nCan:{2}\nGuc:{3}",
Isim, Irk, Can, Guc);
}
}
BTW I think it will be useful for you to read about Value and Reference Types in .NET
You might want to consider using a class instead of a struct.
As said, a struct is a value type and passed by copy. You can pass it by ref like this:
public static void Move (ref Character a)
{
...
}
and call it like this:
var a = new Character();
MainClass.Move(ref a);
Ok so lets say I have a structure A like that:
Struct A{
private String _SomeText;
private int _SomeValue;
public A(String someText, int SomeValue) { /*.. set the initial values..*/ }
public String SomeText{ get { return _SomeText; } }
public int SomeValue{ get { return _SomeValue; } }
}
Now what I want to be able to do is to return that Structure A as a result of a method in a Class ABC, like that:
Class ABC{
public A getStructA(){
//creation of Struct A
return a;
}
}
I don't want any programmer using my library (which will have Struct A and Class ABC and some more stuff) to ever be able to create an instance of Struct A.
I want the only way for it to be created is as a return from the getStructA() method. Then the values can be accessed through the appropriate getters.
So is there any way to set a restrictions like that? So a Structure can't be instantiated outside of a certain class? Using C#, .Net4.0.
Thanks for your help.
---EDIT:----
To add some details on why am I trying to achieve this:
My class ABC has some "status" a person can query. This status has 2 string values and then a long list of integers.
There never will be a need to create an object/instance of "Status" by the programmer, the status can only be returned by "getStatus()" function of the class.
I do not want to split these 3 fields to different methods, as to obtain them I am calling Windows API (p/invoke) which returns similar struct with all 3 fields.
If I was indeed going to split it to 3 methods and not use the struct, I would have to either cache results or call the method from Windows API every time one of these 3 methods is called...
So I can either make a public struct and programmers can instantiate it if they want, which will be useless for them as there will be no methods which can accept it as a parameter. Or I can construct the library in such a way that this struct (or change it to a class if it makes things easier) can be obtained only as a return from the method.
If the "restricted" type is a struct, then no, there is no way to do that. The struct must be at least as public as the factory method, and if the struct is public then it can be constructed with its default constructor. However, you can do this:
public struct A
{
private string s;
private int i;
internal bool valid;
internal A(string s, int i)
{
this.s = s;
this.i = i;
this.valid = true;
}
...
and now you can have your library code check the "valid" flag. Instances of A can only be made either (1) by a method internal to your library that can call the internal constructor, or (2) by the default constructor. You can tell them apart with the valid flag.
A number of people have suggested using an interface, but that's a bit pointless; the whole point of using a struct is to get value type semantics and then you go boxing it into an interface. You might as well make it a class in the first place. If it is going to be a class then it is certainly possible to make a factory method; just make all the ctors of the class internal.
And of course I hope it goes without saying that none of this gear should be used to implement code that is resistant to attack by a fully-trusted user. Remember, this system is in place to protect good users from bad code, not good code from bad users. There is nothing whatsoever that stops fully trusted user code from calling whatever private methods they want in your library via reflection, or for that matter, altering the bits inside a struct with unsafe code.
Create a public interface and make the class private to the class invoking it.
public ISpecialReturnType
{
String SomeText{ get; }
int SomeValue{ get; }
}
class ABC{
public ISpecialReturnType getStructA(){
A a = //Get a value for a;
return a;
}
private struct A : ISpecialReturnType
{
private String _SomeText;
private int _SomeValue;
public A(String someText, int SomeValue) { /*.. set the initial values..*/ }
public String SomeText{ get { return _SomeText; } }
public int SomeValue{ get { return _SomeValue; } }
}
}
What exactly are you concerned about? A structure is fundamentally a collection of fields stuck together with duct tape. Since struct assignment copies all of the fields from one struct instance to another, outside the control of the struct type in question, structs have a very limited ability to enforce any sort of invariants, especially in multi-threaded code (unless a struct is exactly 1, 2, or 4 bytes, code that wants to create an instance which contains a mix of data copied from two different instances may do so pretty easily, and there's no way the struct can prevent it).
If you want to ensure that your methods will not accept any instances of a type other than those which your type has produced internally, you should use a class that either has only internal or private constructors. If you do that, you can be certain that you're getting the instances that you yourself produced.
EDIT
Based upon the revisions, I don't think the requested type of restriction is necessary or particularly helpful. It sounds like what's fundamentally desired to stick a bunch of values together and store them into a stuck-together group of variables held by the caller. If you declare a struct as simply:
public struct QueryResult {
public ExecutionDuration as Timespan;
public CompletionTime as DateTime;
public ReturnedMessage as String;
}
then a declaration:
QueryResult foo;
will effectively create three variables, named foo.ExecutionDuration, foo.CompletionTime, and foo.ReturnedMessage. The statement:
foo = queryPerformer.performQuery(...);
will set the values of those three variables according to the results of the function--essentially equivalent to:
{
var temp = queryPerformer.performQuery(...);
foo.ExecutionDuration = temp.ExecutionDuration
foo.CompletionTime = temp.CompletionTime;
foo.ReturnedMessage = temp.ReturnedMessage;
}
Nothing will prevent user code from doing whatever it wants with those three variables, but so what? If user code decides for whatever reason to say foo.ReturnedMessage = "George"; then foo.ReturnedMessage will equal George. The situation is really no different from if code had said:
int functionResult = doSomething();
and then later said functionResult = 43;. The behavior of functionResult, like any other variable, is to hold the last thing written to it. If the last thing written to it is the result of the last call to doSomething(), that's what it will hold. If the last thing written was something else, it will hold something else.
Note that a struct field, unlike a class field or a struct property, can only be changed either by writing to it, or by using a struct assignment statement to write all of the fields in one struct instance with the values in corresponding fields of another. From the consumer's perspective, a read-only struct property carries no such guarantee. A struct may happen to implement a property to behave that way, but without inspecting the code of the property there's no way to know whether the value it returns might be affected by some mutable object.
We are transfering our code from C++ to C# and due to limited knowledge of C# we are stuck into strange situation. Our problem is:
In c++ we have 2-3 types of class/structures which have pointers to property (std::string), purpose of pointer is to make sure that all the instance for similar object will point to same property. e.g
struct st1{
string strVal;
};
struct st2{
string* strVal;
};
//At time of creation
st1* objst1 = new st1();
st2* objst2 = new st2();
objst2.strVal = &objst1.strVal;
//After this at all point both object will point to same value.
I want this kind of architecture C#, I got some suggestion like:
Declare events
Make code unsafe and use pointers (but I think this will lead to some other problems)
Please let me know if something better and near to C++ can be done here..
In C# all clases are references / pointers. So as long as your property is of class type, you can have same instance in different structures.
But problem can arise when you use string. While it is class and reference property, it is enforced to be imutable. So when you change it, you dont change the instance itself, but you create new copy with those changes.
One solution that comes to mind is to create custom string class, that will simply contain string and use it as your type:
public class ReferenceString
{
public String Value { get; set; }
}
You could use a static property with inheritance:
class thing
{
static string stringThing;
public string StringThing
{
get { return stringThing; }
set { stringThing = value; }
}
}
class thing2 : thing
{
}
Then later:
thing theThing = new thing();
theThing.StringThing = "hello";
thing2 theThing2 = new thing2();
// theThing2.StringThing is "hello"
Is it possible to pass an integer as reference at class initialization and safe the reference?
class Foo {
private int _refVal;
public Foo(ref int val) {
_refval = val; // saves the value, not the reference
}
}
I could use pointers, but then I need an unsafe context.
This is not possible.
Instead, you can use a class with a writable property, like this:
class Reference<T> {
public T Value { get; set; }
public Reference(T value) { Value = value; }
}
Out of interest, why do you need to do this? One integer equal to 5 is equal to another integer equal to 5: if there is some differentiation you want to make between them, the integer value type shouldn't be used - you'd want a class instead.
This is not a direct answer to your question, but as they say improving an algorithm is better than implementing or improving a flawed one; perhaps if you could give us some more context we can help with your more general problem / task as a whole?
Hope that helps!
Wrap it in a custom class I guess.