0

given Struct Point :

public struct Point {
    double x, y;
    Point(double i, double j) {
        x=i;
        y=j;
    }
}

Q1:whats the diffrence between:

Point p;

and

Point p=new Point(2.0,3.0);

as i understood it, in the second part annonymous Point struct is being allocated on the heap, and is being copied bit by bit to the p variable's memory allocated on the stack. am i correct?

Q2:what do i need to do to carry reference to Point instead of allocating it on stack and passing it around by value? (without using unsafe pointers)

class Linear {
    private double m, n;
    ref Point p = new Point(2.0,3.0); // not compiling
} 
2
  • 1
    Should read The Truth about value type Commented Jul 5, 2012 at 10:23
  • 1
    q1: No, you are wrong. q2: Wrap the struct in a 'box' or create a Point class. Commented Jul 5, 2012 at 10:23

4 Answers 4

1
class Wrapper
{
    public Point Point { get; set; }
}

Using a reference type (class) wrapping a value type (struct) you will allocate it in the heap.

Sign up to request clarification or add additional context in comments.

Comments

1

A1: In the first statement you are just declaring the variable, you're not creating an instance of the struct, as you do in the second statement.

A2: You need to use the REF keyword where you are 'giving' the object to another method, not where you are declaring the variable.

Comments

0

I usually create a very simple class if I do not want a valuetype struct. Which would look soemthing like the code below for your example. A class will prevent struct boxing/unboxing performance hits in some situations. But if you have a List<> of structs it is a single block of memory for all data. With List<> of class you get a a single block of pointers to a lot of class instances.

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Point
{
    public double x, y;

    public Point(double i, double j)
    {
        x = i;
        y = j;
    }
}

Comments

0

In the second statement, an anonymous temporary storage location of type Point is created, most likely on the stack, and it it is passed as an implicit ref parameter to a parameterized constructor. After the constructor is complete, the Point variable p is mutated by overwriting each field (public or private) with the corresponding fields in that anonymous temporary, which is then abandoned. Note that the behavior is the same whether or not the struct pretends to be immutable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.