- Home /
C# Syntax Question
Any clues what this is saying? What does the colon mean in this context? Any help is appreciated.
Specifically these 2 lines are confusing me badly:
public Observation(Observation observation, bool isVisible) : this(observation.entity, observation.position, isVisible, observation.timestamp) { }
and
public Observation(Entity entity, bool isVisible) : this(entity, entity.Position, isVisible, Time.time) { }
This is the whole script it is from:
using UnityEngine;
public class Observation
{
public Entity entity
{
get;
private set;
}
public float timestamp
{
get;
private set;
}
public Vector3 position
{
get;
private set;
}
public bool isVisible
{
get;
set;
}
public Observation(Observation observation, bool isVisible) : this(observation.entity, observation.position, isVisible, observation.timestamp) { }
public Observation(Entity entity, bool isVisible) : this(entity, entity.Position, isVisible, Time.time) { }
public Observation(Entity entity, Vector3 position, bool isVisible, float timestamp)
{
this.entity = entity;
this.position = position;
this.isVisible = isVisible;
this.timestamp = timestamp;
}
}
Answer by LK84 · Dec 29, 2016 at 08:04 AM
public Observation(Observation observation, bool isVisible) : this(observation.entity, observation.position, isVisible, observation.timestamp) { }
"this"is a reference to the current instance of the class. In the line above you simply make a call from one constructor to the other. It is equal to:
public Observation(Observation observation, bool isVisible)
{
this.entity=observation.entity;
this.position=observation.position;
this.isVisible=isVisible;
this.timestamp=observation.timestamp;
}
Answer by AurimasBlazulionis · Dec 29, 2016 at 08:14 AM
It calls other constructor using these arguments before executing the constructor called from elsewhere. It is useful for not rewriting the same code if you want to just add a little bit more stuff with more arguments. This can be nested.
Answer by ForbiddenSoul · Dec 29, 2016 at 08:19 AM
This makes sense to me although I have never seen : used in a C# constructor: http://stackoverflow.com/questions/1071148/what-does-this-colon-mean/1071156#1071156
Your answer
![](https://koobas.hobune.stream/wayback/20220612103638im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
initialize with object name 1 Answer
c# syntax ((float>0)?(1):(2)) 2 Answers
Can't add script even though the file name and the class name are the same 1 Answer