473,725 Members | 2,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is there a C# equivilent to the pointer to member operator?

Hi All,

Is there a C# version of the C++ pointer (or reference) to member operator -
..* or ->*

Basically I'd like to write a function that can take an object and an offset
to a member of the object to access. For example in the search function
below I'd like to pass in an offset to the member I'd would like to compare
against (in this case _ForeName), meaning I wouldn't have to write a new
function for each member.

struct Person
{
public string _ForeName;
public string _MiddleName ;
public string _Surname ;
}

bool Search(List<Per son> arr, string strSearch)
{
foreach(Person person in arr)
{
if(person._Fore Name==strSearch ) return true ;
}
return false ;
}

Thanks,

-Liam
Dec 18 '05 #1
9 3296
"rellik" <no****@goaway. net> wrote in
news:4B******** ***********@new sfe5-gui.ntli.net:

Why not just use a string array? To make the code more readable you could use
an enum type to index the array...

EvilRix.
Hi All,

Is there a C# version of the C++ pointer (or reference) to member
operator - .* or ->*

<snip>
Dec 18 '05 #2
rellik wrote:
Is there a C# version of the C++ pointer (or reference) to member
operator - .* or ->*

Basically I'd like to write a function that can take an object and an
offset to a member of the object to access. For example in the search
function below I'd like to pass in an offset to the member I'd would
like to compare against (in this case _ForeName), meaning I wouldn't
have to write a new function for each member.


Normally, you have no guarantee as to the memory layout of a struct. You
can use [StructLayout] to force a memory layout (LayoutKind.Exp licit),
but this might not be the most efficient in terms of memory access.

In the past you could use reflection and guarantee that the members
would be in the same order everytime the code is run, but apparently
with .NET 2.0 this is no longer the case. If you use LayoutKindExpli cit
and use [FieldOffset] on members, then you can use reflection
(FieldInfo.GetC ustomAttributes ) to get the FieldOffsetAttr ibute and test
the Value to see if it is the offset that you require. Not the best
solution.

Richard
--
Fusion Tutorial: http://www.grimes.demon.co.uk/workshops/fusionWS.htm
Security Tutorial:
http://www.grimes.demon.co.uk/workshops/securityWS.htm
Dec 18 '05 #3
"Richard Grimes" <ri******@mvps. org> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
rellik wrote:

Normally, you have no guarantee as to the memory layout of a struct. You
can use [StructLayout] to force a memory layout (LayoutKind.Exp licit), but
this might not be the most efficient in terms of memory access.

In the past you could use reflection and guarantee that the members would
be in the same order everytime the code is run, but apparently with .NET
2.0 this is no longer the case. If you use LayoutKindExpli cit and use
[FieldOffset] on members, then you can use reflection
(FieldInfo.GetC ustomAttributes ) to get the FieldOffsetAttr ibute and test
the Value to see if it is the offset that you require. Not the best
solution.

Richard
--


Thanks Richard, that's most informative. While on balance C# is an great
language, coming from C++ I keep finding restrictions upon the way I would
normally engineer a solution. In this case I may just write a few versions
of the same function as performance will be an issue.

-Liam
Dec 18 '05 #4
rellik wrote:
"Richard Grimes" <ri******@mvps. org> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
rellik wrote:

Normally, you have no guarantee as to the memory layout of a struct. You
can use [StructLayout] to force a memory layout (LayoutKind.Exp licit), but
this might not be the most efficient in terms of memory access.

In the past you could use reflection and guarantee that the members would
be in the same order everytime the code is run, but apparently with .NET
2.0 this is no longer the case. If you use LayoutKindExpli cit and use
[FieldOffset] on members, then you can use reflection
(FieldInfo.Ge tCustomAttribut es) to get the FieldOffsetAttr ibute and test
the Value to see if it is the offset that you require. Not the best
solution.

Richard
--

Thanks Richard, that's most informative. While on balance C# is an great
language, coming from C++ I keep finding restrictions upon the way I would
normally engineer a solution. In this case I may just write a few versions
of the same function as performance will be an issue.

-Liam

There is no need to write the same function all over again. You can use
List<T>.Find and just rewrite the functor:

class MatchByForeName
{
public static Predicate<Perso n> Create(string foreName)
{
return (new MatchByForeName (foreName)).Mat ch;
}
private MatchByForeName (string foreName)
{
this.forename = foreName;
}
private bool Match(Person p)
{
return p._ForeName == forename;
}
string forename = string.Empty;
}

//
Person p = arr.Find(MatchB yForeName.Creat e(strSearch));
HTH,
Andy
Dec 18 '05 #5
> There is no need to write the same function all over again. You can use
List<T>.Find and just rewrite the functor:

Hi Andy,

There's been a misunderstandin g - it's probably my fault but my problem had
nothing to do with string compares, it was just the simplest example that
came to mind. I was after a generic pointer to member facility it C#. It
appears there is none.

After giving it some though I've decided to use generics and anonymous
delegates and I am quite happy with it. Here's some sample code.

public bool DoIt(Person p,GetPtrMember< string,Person> getVal)

{

return getVal(p)=="hel lo";

}

private void button1_Click(o bject sender, EventArgs e)

{

Person p = new Person();

bool bRet = DoIt(p, new GetPtrMember<st ring,Person>(de legate(Person pIn) {
return pIn._strForenam e; }));

}

public delegate Ret GetPtrMember<Re t,Typ>(Typ a) ;

public class Person

{

public string _strForename="h ello";

public string _strSurname="wo rld";

}

There are a number of flaws in this approach. 1. Performance, 2. The member
has to be public or have a public property.

Still, it'll do for now.

-Liam
Dec 18 '05 #6

"Richard Grimes" <ri******@mvps. org> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
rellik wrote:
Is there a C# version of the C++ pointer (or reference) to member
operator - .* or ->*

Basically I'd like to write a function that can take an object and an
offset to a member of the object to access. For example in the search
function below I'd like to pass in an offset to the member I'd would
like to compare against (in this case _ForeName), meaning I wouldn't
have to write a new function for each member.
Normally, you have no guarantee as to the memory layout of a struct. You
can use [StructLayout] to force a memory layout (LayoutKind.Exp licit), but
this might not be the most efficient in terms of memory access.


In the past you could use reflection and guarantee that the members would
be in the same order everytime the code is run, but apparently with .NET
2.0 this is no longer the case.


Where did you get this from?
As far as I know the struct (value type) lay-out is still guaranteed to be
arranged in the order as specified in the definition, provided one the
StructLayoutAtt ribute.Sequenti al or StructLayoutAtt ribute.Explicit is
applied.

Willy.
Dec 18 '05 #7
rellik <no****@goaway. net> wrote:
Thanks Richard, that's most informative. While on balance C# is an great
language, coming from C++ I keep finding restrictions upon the way I would
normally engineer a solution. In this case I may just write a few versions
of the same function as performance will be an issue.


Yes, C# is a different language with different idioms. If you find that
C# is "resisting" the solution you'd use in C++, that's usually a sign
that it's not the best way to accomplish the larger goal in C#. It's
definitely not worth trying to force C# into a C++-like shape :)

Depending on exactly what you need to do, you could write three methods
which take List<Person> return Enumerator<stri ng>, then use those in
various places wherever you wanted to write a general method like
Search.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 19 '05 #8
rellik wrote:
There is no need to write the same function all over again. You can use
List<T>.Fin d and just rewrite the functor:


Hi Andy,

There's been a misunderstandin g - it's probably my fault but my problem had
nothing to do with string compares, it was just the simplest example that
came to mind. I was after a generic pointer to member facility it C#. It
appears there is none.

After giving it some though I've decided to use generics and anonymous
delegates and I am quite happy with it. Here's some sample code.

public bool DoIt(Person p,GetPtrMember< string,Person> getVal)

{

return getVal(p)=="hel lo";

}

private void button1_Click(o bject sender, EventArgs e)

{

Person p = new Person();

bool bRet = DoIt(p, new GetPtrMember<st ring,Person>(de legate(Person pIn) {
return pIn._strForenam e; }));

}

public delegate Ret GetPtrMember<Re t,Typ>(Typ a) ;

public class Person

{

public string _strForename="h ello";

public string _strSurname="wo rld";

}

There are a number of flaws in this approach. 1. Performance, 2. The member
has to be public or have a public property.

Still, it'll do for now.

-Liam

Hi Liam,
sorry for my my bad explanation. I basically meant the same thing that
you outlined in you code. My point was that you just have to rewrite the
access to the field and encapsulate it into an object and that a lot of
collections now have basic algorithms taking such functors.

on (1)
From my experience, your solution should perform extremely fast. As I
use a similar technique in a performance critical section of my project
I'm interested where you are having problems.

on (2): the member has to be accessible, not necessary public: Make the
field private. Then you can provide a property in two ways:
-An internal property.
-Define the properties in an interface. Let you other methods operate on
the interface and the Person class implements the interface *explicitly*.

HTH,
Andy
Dec 19 '05 #9
"Andreas Mueller" <me@privacy.net > wrote in message
news:40******** *****@individua l.net...
rellik wrote:
Hi Liam,
sorry for my my bad explanation. I basically meant the same thing that you
outlined in you code. My point was that you just have to rewrite the
access to the field and encapsulate it into an object and that a lot of
collections now have basic algorithms taking such functors.

on (1)
From my experience, your solution should perform extremely fast. As I use
a similar technique in a performance critical section of my project I'm
interested where you are having problems.
I tested it today and was indeed quite happy with the performance. Obviously
not as fast as a native c++ version with a simple offset but more than
adequate for the job in hand.

on (2): the member has to be accessible, not necessary public: Make the
field private. Then you can provide a property in two ways:
-An internal property.
-Define the properties in an interface. Let you other methods operate on
the interface and the Person class implements the interface *explicitly*.


Cheers Andy, I implemented your suggestion and am now more than happy with
the results.

-Liam
Dec 19 '05 #10

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

Similar topics

3
1855
by: jimjim | last post by:
Hello, My question concerns as to how a pointer is passed by reference as a function argument. The following is from code taken from the MICO implementation of the CORBA specification. in include files: typedef Context *Context_ptr; typedef ObjOut<Context> Context_out;
6
3178
by: | last post by:
Say we have the following code defining TMyMsgHandler and TMyClass typedef void (*TOnMsgReceive) (TMyMessage Msg); class TMyMsgHandler { public: TMyMsgHandler(); virtual ~TMyMsgHandler(); TOnMsgReceive *OnMsgReceive; };
40
3025
by: Steve Rencontre | last post by:
I can't for the life of me see how to do pointer-to-member when the member is actually part of an embedded structure. That is, if I have: struct S1 { int a; }; struct S2 { S1 s; int b; }; how can I get a pointer to the a in an S2?
33
5065
by: Ney André de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the actual counting. Here is the latter's definition: // --- Begin ReferenceCountable.h ---------- class ReferenceCountable
6
4154
by: Caleb | last post by:
I have a class that has two member functions of the same name: class MyClass { public: void someFunction(int arg); void someFunction(int arg, char blah); }; I'm trying to get a tr1::functional to the first one, for example:
9
3205
by: Cyron | last post by:
Hello friends, Recently I have begun exploring the features that the STL map collection provides. While learning how it worked, I encountered a result that confused me. Up until now, I had always been under the impression that if I had a pointer variable, p which contained the member "first", I could access this member variable either by: (*p).first OR p->first . That is, in general I thought p->x was just shorthand for (*p).x ?
12
540
by: WaterWalk | last post by:
Hello. I am rather confused by the type of a pointer to class data member. Many c++ texts say that pointer to data member has a special syntax. For example the following class: class MyClass { public: int n; }; The pointer to MyClass.n shall be defined like this:
5
4657
by: Tim Frink | last post by:
Hi, I'm experimenting with function pointers and found two questions. Let's assume this code: 1 #include <iostream> 2 class A; 3 4 //////////////////////////////////////////// 5 class B
31
1971
by: huili80 | last post by:
Say I have two classes: class A { public: int x; }; class B {
0
8749
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
9252
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9168
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9103
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
6009
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();...
0
4508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4779
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2631
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2154
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.