Click here to Skip to main content
15,881,804 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in the following code, how do u convert 'find' from C++ to C#?
in another words, how to return a reference to an object in C#?
C++
struct MyStruct
{
    int id;
    ...
} list[]=
{
    ...
};

MyStruct &find(int id)
{
    for (int i=0; i<_countof(list); i++)
        if (id == list[i].id)
            return list[i];
    static MyStruct empty={0,...};
    return empty;
}
Posted

 
Share this answer
 
Use the ref keyword or (out in your case because you want to (possible) reassign the pointer (when you return the empty struct))

http://msdn.microsoft.com/en-us/library/14akc2c7(v=vs.71).aspx[^]

Btw: I think this pattern is not "state of the art" for .net.
 
Share this answer
 
Comments
ilostmyid2 15-Mar-12 8:36am    
yeah, ur both right. but what i want to do is a bit different. when returning result via arguments there's no problem, but i want to return the reference from function.
johannesnestler 15-Mar-12 8:41am    
I think you have a missunderstanding what a reference means for .net (I come from c++ too, I also had my problems first...)
ilostmyid2 15-Mar-12 9:22am    
misunderstanding?! what's the correct meaning?
As an alternative, the following code may be tried
C#
struct MyStruct {
    public int Id;
       
    public MyStruct(int id){
        Id=id;
    }
}

var list = new List<mystruct>();
	
//add items to the list
list.Add(new MyStruct(5));
list.Add(new MyStruct(10));
//To find an item of list matching an Id say 5 use the Find method with a predicate
MyStruct foundStruct = list.Find(myStruct => myStruct.Id == 5);
 
Share this answer
 
v2
Comments
johannesnestler 15-Mar-12 9:00am    
yea, this is modern .net style - better then mine - 5ed
ProEnggSoft 15-Mar-12 9:32am    
Thank you!
ilostmyid2 15-Mar-12 9:17am    
the same problem with Solution 3 exists here too:
private static void Main(string[] args)
{
var list = new List<mystruct>();

//add items to the list
list.Add(new MyStruct(5));
list.Add(new MyStruct(10));
//To find an item of list matching an Id say 5 use the Find method with a predicate
MyStruct foundStruct = list.Find(myStruct => myStruct.Id == 5);
foundStruct.Id = 1;
Console.WriteLine("list[0].Id={0}", list[0].Id);
Console.ReadKey();
}
here list[0].Id is still 5. this indicates that foundStruct is a separate object than list[0], not to be a reference to it.
ProEnggSoft 15-Mar-12 9:22am    
I got your point.
In .NET struct is a Value Type. So, when the Find method is executed, a copy of item in the list is returned. Please see my Solution(5).
In .Net, pass-by-reference or by-value is a feature of the type itself. If you want to be able to get references to an object, you need to make its type a class, not a struct (which is a value type).

In this case MyClass needs to be a class:
class MyClass {
 int id;
 // ...
}


and you need to just return something of type MyClass:
List<MyClass> list;

MyClass find(int id){
 foreach(MyClass item in list)
  if(item.id == id) return item;
 return null;
}


Note that you don't actually have to write this at all, though, if you're in .Net 3.5 or 4, because you can use System.Linq extension methods to write
MyClass theOneIWant = list.FirstOrDefault(c => c.id == id);
 
Share this answer
 
Comments
ilostmyid2 15-Mar-12 11:01am    
it's interesting! so => is added by System.Linq? how is it possible? the compiler must be ready for the syntax. FirstOrDefault must be method of List. how can a special using namespace add a method to a class which is normally not in the class?!
BobJanova 15-Mar-12 12:56pm    
No, the => syntax for defining lambda functions is a part of the language. You can, for example, use it to define event handlers:

myButton.Click += (s, e) => { some stuff with s and e };

System.Linq defines a lot of extension methods (such as FirstOrDefault, Where, Select), mostly against IEnumerable<T> (which List<T> implements) which take functions (which you can declare as lambdas) as parameters that define how to filter, convert, compare etc.

There's really more going on than can be explained in a comment here; searching for 'Linq tutorial' and 'C# lambda' should get you some useful introductory material.
ilostmyid2 15-Mar-12 14:40pm    
thx, i will study more about it.
I'd implement the whole thing like this:

namespace ReferencesOhMy
{
    class Program
    {
        struct MyStruct
        {
            public int Id;
        }

        static MyStruct[] list = new MyStruct[]
            {
                new MyStruct() { Id = 1 },
                new MyStruct() { Id = 2 }
            };

        static MyStruct find(int id)
        {
            for (int i = 0; i < list.Length; i++)
                if (id == list[i].Id)
                    return list[i];
            return new MyStruct() { Id = 0 };
        }

        static void Main(string[] args)
        {
            MyStruct mystruct = find(1); // reference to your original list object
            MyStruct mystructEmpty = find(999); // empty
        }
    }
}


so no need for any ref or out... (I think, if you need it somethings wrong - except for working with legacy code)
 
Share this answer
 
v2
Comments
ilostmyid2 15-Mar-12 9:06am    
indeed what find returns in your code is not the same object existing in the list. i need a reference to that object. for example if i change the Main function to this:
static void Main(string[] args)
{
MyStruct mystruct = find(1); // reference to your original list object
mystruct.Id = 5;
Console.WriteLine("list[0].id = {0}", list[0].Id);
Console.ReadKey();
MyStruct mystructEmpty = find(999); // empty
}
you see that list[0].Id is still 1, not 5!
For the purpose shown by OP in comments under Solution 4, Reference type (class) is used.
C#
static void Main()
{

    List<myclass> list = new List<myclass>();
    
    //Add items to the list
    list.Add(new MyClass(5));
    list.Add(new MyClass(10));
    //To find an item in the list, matching an Id say 5, use the 
    //Find method with a predicate
    MyClass foundItem = list.Find(MyClass => MyClass.Id == 5);
    Console.WriteLine (list[0].Id);
    foundItem.Id=15;
    Console.WriteLine (list[0].Id);
    //Output:
    //5
    //15
}


class MyClass {
    public int Id {get; set;}

    public MyClass(int id){
        Id=id;
    }
}
 
Share this answer
 
v4
Comments
ilostmyid2 15-Mar-12 9:57am    
oh thx, i got it! :)
ProEnggSoft 15-Mar-12 10:53am    
OK. No problem

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900