473,224 Members | 1,344 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,224 software developers and data experts.

Question about Class Methods

Hi,

Lets say I have a class called Point and I give this class the
following properties -

int[] CoordinatesInPixels{...}
float[] CoordinatesInInches{...}

And the Method -

bool IsInFirstQuadrant(){...}

My question is, if I create two objects of this class, do I have two
instances for each of the two properties and two instances of the
IsInFirstQuadrant() method stored in memory. That is, does all the
code need to execute IsInFirstQuadrant get loaded into memory twice,
or is the address of point1.IsInFirstQuadrant() equal to that of
point2.IsInFirstQuadrant().

Thanks for your help,

Barry.
Sep 1 '08 #1
8 1083
Methods are only loaded once (assuming a single AppDomain etc).
Properties are actually just named methods too - the only thing that
takes space per instance is the object header itself, and any fields
(instance variables for the type). Since arrays are reference-types,
each instance will require space for the 2 references. Assuming the
array data is separate per instance, then each instance will also have a
corresponding block of data on the manged heap for each array itself.

Marc
Sep 1 '08 #2
<Ma*************@gmail.comwrote in message
news:6a**********************************@y21g2000 hsf.googlegroups.com...
My question is, if I create two objects of this class, do I have two
instances for each of the two properties and two instances of the
IsInFirstQuadrant() method stored in memory. That is, does all the
code need to execute IsInFirstQuadrant get loaded into memory twice,
In addition to marc's response, the way it works is quite interesting. There
is only ever one function created no matter how many objects exist in
memory. So how can that one function work when there are multiple instances
of your class? Simple, a pointer to your class is passed into that function,
eg If you have this

class MyClass
{
public void DoIt()
{
}
}

Then a single function is defined that looks like this:

void DoIt(MyClass* this)
{
}

the DoIt function knows which module level variables to use by the 'this'
pointer. That way 1 function can work accross thousands of instances of your
class.

Disclaimer: To be honest I don't know the internal working of dot net too
well but this is how it works in other languages so I'd be suprised if it
was vastly different here. I'm sure Peter Dunnydore will chime in if it is.
There may even be other additional hidden parameters. It's pretty much the
same as non oop code where you would get a handle to an object, eg

int handle = CreateThingy();
ThingyDoSomething(handle, 1, 2, 3, 4);

dot net just wraps it all up nicely for you to create the concept of an
object:

Thingy t = new Thingy();
t.DoSomething(1, 2, 3, 4);

Michael
Sep 1 '08 #3
so I'd be suprised if it was vastly different here.

It is, indeed, the same in .NET (and C# in particular). The only
subtlety is that the "this" parameter is not named, with the compiler
just using the "ldarg.0" op-code in place of "this" in the body.

With C# 3 you can replicate a similar setup with "extension methods",
except the arg *is* named, and there is no virtcall involved (with the
interesting side-effect that you can call "instance" extension methods
on null instances).

Marc
Sep 1 '08 #4
On Sep 1, 2:14*pm, Marc Gravell <marc.grav...@gmail.comwrote:
*so I'd be suprised if it was vastly different here.

It is, indeed, the same in .NET (and C# in particular). The only
subtlety is that the "this" parameter is not named, with the compiler
just using the "ldarg.0" op-code in place of "this" in the body.
One more subtlety: for value types, the implicit "this" parameter is
passed by reference. Most of the time this isn't important (as value
types should almost always be immutable) but it matters when you're
trying to create an open delegate...

Jon
Sep 1 '08 #5
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:460697db-cdc0-4cda-a843-
>One more subtlety: for value types, the implicit "this" parameter is
passed by reference. Most of the time this isn't important (as value
t>ypes should almost always be immutable) but it matters when you're
>trying to create an open delegate...
Can you elaborate on that?

Jon
Sep 2 '08 #6
"Michael C" <mi***@nospam.comwrote in message
news:uF**************@TK2MSFTNGP03.phx.gbl...
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:460697db-cdc0-4cda-a843-
>>One more subtlety: for value types, the implicit "this" parameter is
passed by reference. Most of the time this isn't important (as value
t>ypes should almost always be immutable) but it matters when you're
>>trying to create an open delegate...

Can you elaborate on that?
It means that when you write something like this:

struct Foo
{
int x, y;
void Bar() { ... }
}

the actual signature of the method in runtime is more like:

static void Bar(ref Foo this);

which is why you can change values of struct fields in your methods, and
they persist. But it has some other interesting side effects. For example,
given this:

void Swap<T>(ref T x, ref T y);

you could write Foo.Bar like this:

void Bar()
{
Foo other;
...
Swap(ref this, other);
}

and it also allows for the following puzzling syntax in constructors and
methods:

Foo()
{
this = new Foo(1, 2);
}
Sep 2 '08 #7
On Sep 2, 6:34*am, "Pavel Minaev" <int...@gmail.comwrote:

<snip - yup, that's what I meant>
and it also allows for the following puzzling syntax in constructors and
methods:

* Foo()
* {
* * this = new Foo(1, 2);
* }
Except that you can't define your own parameterless constructor for a
struct ;)

The point about open delegates is best shown with some code. Note how
the delegate type I use for the class has a by-value first parameter
whereas the one for the struct has a by-ref first parameter.

using System;
using System.Reflection;

struct ValueType
{
readonly string name;

public ValueType(string name)
{
this.name = name;
}

public void Foo(int x)
{
Console.WriteLine("{0}: {1}", name, x);
}
}

class RefType
{
readonly string name;

public RefType(string name)
{
this.name = name;
}

public void Foo(int x)
{
Console.WriteLine("{0}: {1}", name, x);
}
}

delegate void ValueFoo(ref ValueType v, int i);
delegate void RefFoo(RefType v, int i);

class Test
{
static void Main()
{
MethodInfo valueInfo = typeof(ValueType).GetMethod("Foo");
MethodInfo refInfo = typeof(RefType).GetMethod("Foo");

ValueFoo valueDel = (ValueFoo) Delegate.CreateDelegate
(typeof(ValueFoo), valueInfo);

RefFoo refDel = (RefFoo) Delegate.CreateDelegate
(typeof(RefFoo), refInfo);

ValueType vt = new ValueType("val");
RefType rt = new RefType("ref");

valueDel(ref vt, 10);
refDel(rt, 20);
}
}

Jon
Sep 2 '08 #8
Can you elaborate on that?

An open delegate is where we get the runtime to treat the "this"
argument as simply the first argument, as though it were a static
method. The problem is that the delegate still needs to meet the
declared signature. So with a reference-type (class):

public class X {
public void Y() {...}
}

You can get an open Action<Xdelegate to Y(), and pass in the X at
runtime:

Action<Xaction = ...
Y y = ...
action(y);

However, with a value-type, the open-delegate can't use Action<X>,
since this doesn't have "ref" on the first argument (you get a bind
failure); you need to use a delegate that uses "ref" on the first
argument. A full example is below.

Marc

using System;
struct Foo
{
private readonly int bar;
public int Bar { get { return bar; } }
public Foo(int bar)
{
this.bar = bar;
}
public void Test()
{
this = new Foo(Bar + 1);
}
}
delegate void RefAction<T>(ref T foo);
static class Program
{
static void Main()
{
Foo foo = new Foo(1);
Console.WriteLine("Init: {0}", foo.Bar);
foo.Test();
Console.WriteLine("After Test: {0}", foo.Bar);

RefAction<FooopenDelegate =
(RefAction<Foo>)Delegate.CreateDelegate(
typeof(RefAction<Foo>),
typeof(Foo).GetMethod("Test"));

openDelegate(ref foo);
Console.WriteLine("After Delegate Invoke: {0}", foo.Bar);
}
}
Sep 2 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Dave Rahardja | last post by:
OK, so I've gotten into a philosophical disagreement with my colleague at work. He is a proponent of the Template Method pattern, i.e.: class foo { public: void bar() { do_bar(); } protected:...
51
by: Casper Bang | last post by:
My question is fundamental I beleive but it has been teasing me for a while: I have two classes in my app. The first class is instantiated as a member of my second class. Within this first class,...
14
by: 42 | last post by:
Hi, Stupid question: I keep bumping into the desire to create classes and properties with the same name and the current favored naming conventions aren't automatically differentiating them......
7
by: Bob Morvay | last post by:
I am trying to determine how far I should go in encapsulating data. As I understand it, OO practices state to create private member variables and use these variables in your publicly accessible...
7
by: Joe Fallon | last post by:
I have a WinForm that is a Base class. It has many controls on it and a lot of generic code behind. When I inherit the form I override 5 methods and now each child form has the same look and feel...
6
by: Peter Oliphant | last post by:
I just discovered that the ImageList class can't be inherited. Why? What could go wrong? I can invision a case where someone would like to add, say, an ID field to an ImageList, possible so that...
7
by: Steve Long | last post by:
Hello, I have a design question that I'm hoping someone can chime in on. (I still using VS 2003 .NET 1.1 as our company has not upgraded XP to sp2 yet. duh I know, I know) I have a class I wrote...
10
by: Frank Millman | last post by:
Hi all I recently posted a question about subclassing. I did not explain my full requirement very clearly, and my proposed solution was not pretty. I will attempt to explain what I am trying to...
7
by: jason | last post by:
In the microsoft starter kit Time Tracker application, the data access layer code consist of three cs files. DataAccessHelper.cs DataAcess.cs SQLDataAccessLayer.cs DataAcccessHelper appears...
23
by: neoedmund | last post by:
There's a program, it's result is "unexpected aaa", i want it to be "expected aaa". how to make it work? class C1(object): def v(self, o): return "expected "+o class C2(object):
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.