c# - Getting Value from dictionary, when the key in an object -


i have object pixeldata:

public class pixeldata {    public int x {get;set;}    public int y {get;set;} } 

pixel data key dictionary.

dictionary<pixeldata, int> dict 

how use pixel data right way?

a simple solution use struct instead of class pixeldata:

public struct pixeldata {     public int x;     public int y; }  var dict = new dictionary<pixeldata, int>(); 

you can read differences between structs , classes in c# here. short version: structs value types, unlike classes reference types. therefore, if want retrieve value dictionary, don't need reference original pixeldata instance used key. can go ahead , create new instance, exact same x , y used key, , work fine.

// add new value dictionary new pixeldata instance key dict.add(new pixeldata { x = 1, y = 1 }, 42);   // retrieving value using new, identical instance of pixeldata works fine int value = dict[new pixeldata { x = 1, y = 1 }]); 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -