Click here to Skip to main content
14,331,710 members
Rate this:
Please Sign up or sign in to vote.
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#?
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
Rate this:
Please Sign up or sign in to vote.

Solution 2

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.
   
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?
Rate this:
Please Sign up or sign in to vote.

Solution 4

As an alternative, the following code may be tried
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);
   
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).
Rate this:
Please Sign up or sign in to vote.

Solution 6

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);
   
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.
Rate this:
Please Sign up or sign in to vote.

Solution 3

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)
   
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!
Rate this:
Please Sign up or sign in to vote.

Solution 5

For the purpose shown by OP in comments under Solution 4, Reference type (class) is used.
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;
    }
}
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100