Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting query .Net C#

Tags:

c#

.net

casting

wpf

Can someone please explain why this works:

RibbonTab rt_selecteda = (RibbonTab)MainWindow.Ribbon_Main_Link.SelectedItem;
string a = rt_selecteda.Tag.ToString();

but this fails:

string ab = (RibbonTab)MainWindow.Ribbon_Main_Link.SelectedItem.Tag.ToString();

'object' does not contain a definition for 'Tag' and no extension method 'Tag' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) W:\Dev_Code\Reporting_App\Core\Ribbon_Common.cs 114 78 Reporting_App

like image 893
user3329538 Avatar asked Aug 23 '26 17:08

user3329538


2 Answers

This

string ab = (RibbonTab)MainWindow.Ribbon_Main_Link.SelectedItem.Tag.ToString();

is not the same as (note the brackets)

string ab = ((RibbonTab)MainWindow.Ribbon_Main_Link.SelectedItem).Tag.ToString();

which is the one-line equivalent to your first code

RibbonTab rt_selecteda = (RibbonTab)MainWindow.Ribbon_Main_Link.SelectedItem;
string a = rt_selecteda.Tag.ToString();
like image 96
Rafa Paez Avatar answered Aug 25 '26 07:08

Rafa Paez


(RibbonTab)MainWindow.Ribbon_Main_Link.SelectedItem.Tag.ToString() means:

  1. Take MainWindow.Ribbon_Main_Link.SelectedItem

  2. Get its Tag property

  3. Call the Tag's ToString method

  4. Cast the result as an RibbonTab

This fails since a. MainWindow.Ribbon_Main_Link.SelectedItem is of type object and doesn't have a Tag property, and b. even if it had, ToString returns a string and you can't cast a string as a RibbonTab.

like image 26
Benesh Avatar answered Aug 25 '26 08:08

Benesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!