Object initializers and the Geodatabase API
This post was provided by geodatabase product engineer James MacKay
A new approach to initializing objects was introduced at .NET 3.0: object initializers. These allow objects to be instantiated and initialized in a single line, provided the class has a constructor with an appropriate accessibility level. An instance of an ESRI.ArcGIS.Geometry.Point can be created using the following code at .NET 3.0:
IPoint point = new PointClass { X = 3.5, Y = 5.8 };
There are numerous places in the Geodatabase API where this is handy, especially where multiple interfaces are required to initialize an object that would otherwise require casting (i.e. using IQueryFilter and IQueryFilterDefinition to initialize a query filter). Here are a few key examples:
IQueryFilter queryFilter = new QueryFilterClass { WhereClause = "PID > 40", PostfixClause = "ORDER BY PID" };
IDatasetName datasetName = new FeatureClassNameClass { Name = "Parcels", WorkspaceName = wsName };
ILine line = new LineClass{ FromPoint = point1, ToPoint = point2 };
There are some situations where this approach should be avoided, however:
- When property assignment can raise an error; using object initializers can complicate debugging.
- Where there are several inherited interfaces implemented by the class, i.e. Field objects. Due to the way members are named at the class level, the code can become difficult to read.