Answered linq and refrence object

  • Wednesday, April 16, 2008 10:43 AM
     
     

     

    hi everybody

    I have a method by following signature and body:
    private void LoadByItem(Item item)
    {
    MyDBDataContext my = new MyDBDataContext();
    var query = from q in my.Items
    where q.Id == item.Id
    select q;
    item = query.First<Item>>;
    }

    when I send the argument to the above method, after method process I get nothing in item while in the method item had value. I think after assigning item to query it work as a value type not a reference type.
    please let me know how can I get the reference of item without using ref in function signature.

All Replies

  • Friday, April 18, 2008 9:12 AM
     
     Answered

    Hi toorani,

    So you problem is how to output the parameter Item in your Method above, is not it?

    As far as I know, there is two type variable in C#, reference type and value type, it you use the reference type, you can pass it by reference without the ref key word, and any class in C# in a reference type, if you define the Item as class, you can implement the function what you want.

    Code Snippet

    Item item1 = new Item();

    LoadByItem(item1); //output the parameter ok

    class Item

        {

          public  int test_value;

        }

     

    Alternative solution for ref key word, the out key word has the same result.

    Regards,

    Xun

     

  • Friday, April 18, 2008 2:11 PM
     
     
    I have done the test and in my case works fine. try use DataContext.Log or use a profiler to see if the query is executed, and ensure that the query performed returns record. Maybe that is the problem.

    Another thing

    item = query.First<Item>>; this is wrong
    gives the error Cannot convert method group 'First' to non-delegate type

    use
     
    item = query.First<Item>();