473,800 Members | 2,647 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about Class Methods

Hi,

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

int[] CoordinatesInPi xels{...}
float[] CoordinatesInIn ches{...}

And the Method -

bool IsInFirstQuadra nt(){...}

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
IsInFirstQuadra nt() method stored in memory. That is, does all the
code need to execute IsInFirstQuadra nt get loaded into memory twice,
or is the address of point1.IsInFirs tQuadrant() equal to that of
point2.IsInFirs tQuadrant().

Thanks for your help,

Barry.
Sep 1 '08 #1
8 1102
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.comwrot e in message
news:6a******** *************** ***********@y21 g2000hsf.google groups.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
IsInFirstQuadra nt() method stored in memory. That is, does all the
code need to execute IsInFirstQuadra nt 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();
ThingyDoSomethi ng(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...@g mail.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.co mwrote 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.c omwrote in message
news:uF******** ******@TK2MSFTN GP03.phx.gbl...
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote 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.c omwrote:

<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.Reflecti on;

struct ValueType
{
readonly string name;

public ValueType(strin g name)
{
this.name = name;
}

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

class RefType
{
readonly string name;

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

public void Foo(int x)
{
Console.WriteLi ne("{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(ValueTyp e).GetMethod("F oo");
MethodInfo refInfo = typeof(RefType) .GetMethod("Foo ");

ValueFoo valueDel = (ValueFoo) Delegate.Create Delegate
(typeof(ValueFo o), valueInfo);

RefFoo refDel = (RefFoo) Delegate.Create Delegate
(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<Xdelegat e 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>(re f T foo);
static class Program
{
static void Main()
{
Foo foo = new Foo(1);
Console.WriteLi ne("Init: {0}", foo.Bar);
foo.Test();
Console.WriteLi ne("After Test: {0}", foo.Bar);

RefAction<Fooop enDelegate =
(RefAction<Foo> )Delegate.Creat eDelegate(
typeof(RefActio n<Foo>),
typeof(Foo).Get Method("Test")) ;

openDelegate(re f foo);
Console.WriteLi ne("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
3629
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: virtual void do_bar() {} };
51
4323
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, a method (event) needs to be able to invoke methods of the second class. With static classes its possible but this is not desirable. There's obviouly some visibility problem I am not familiar with. It is not a parent-child relationship since...
14
3144
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... (both are "Pascal Case" with no leading or trailing qualifiers). For example... I'll be modelling something, e.g. a computer, and I'll
7
1357
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 functions. This requires the programmer to set the variables using the setters of the class before calling the function. The problem that I see is that the coder doesn't know the private variables needed by the public function without viewing the...
7
1267
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 and functionality. This part all works fine. (I learned this morning that if you override a method that also has an Event Handler then you should NOT include the event handler a 2nd time. I had a devil of a time figuring out why a block of code...
6
1771
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 the individual elements in an array of ImageList's could be identified by the ID, thereby allowing re-ordering the array without harm. A person could identify by index into the array, but that would not be preserved by re-ordering (and re-ordering...
7
308
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 (CAppInit) that I use for application configuration. It behaves similarly to Configuration.AppSettings with some extra functionality. This class is in an assembly (AppConfiguration) with another class. I would now like to extend the functionality...
10
1207
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 do more fully, and describe a possible solution. It is still not pretty, so I would appreciate any comments. I have a base class (ClassA), which is an abstract class. Most of the methods and attributes are common to all subclasses, so there is...
7
4476
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 to be checking that the correct data type is used DataAcess sets an abstract class and methods
23
1520
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):
0
9694
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9553
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10039
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9095
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7584
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6824
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4152
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3765
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2953
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.