I'm from a dialect speaking part of Norway (Hallingdal), and my peers and I would speak like Oslo (so closer to bokmål) together. But they would always speak in dialect with teachers, their parents etc. My parents are foreigners, so I then never picked up on speaking the dialect myself. But it's still a shock to have a conversation with them, and how they suddenly switch when picking up the phone or whatever.
Not entirely sure why they switch. Was it to "be cool" with friends? Or to suck it a bit up to authority figures?